I wan to convert a string for example 1,2,3,4,5,6 to an array of integers in php? I find functions that only have access to the first character of the string for example 1.
Use PHP's explode.
$str = "1,2,3,4,5,6";
$arr = explode("," $str); // array( '1', '2', '3', '4', '5', '6' );
foreach ($arr AS $index => $value)
$arr[$index] = (int)$value;
// casts each value to integer type -- array( 1, 2, 3, 4, 5, 6 );
As suggested by Tim Cooper, using array_walk is simpler than the above loop:
array_walk($arr, 'intval');
The above answers could potentially return non-numeric values
Both return arrays that are tainted with non-numeric values.
$string = ',g,6,4,3,f,32,a,';
$array = explode(',', $string);
array_walk($array, 'intval');
$arrayMap = array_map('intval', $array);
var_dump($array);
var_dump($arrayMap);
/*
array(9) {
[0]=>
string(0) ""
[1]=>
string(1) "g"
[2]=>
string(1) "6"
[3]=>
string(1) "4"
[4]=>
string(1) "3"
[5]=>
string(1) "f"
[6]=>
string(2) "32"
[7]=>
string(1) "a"
[8]=>
string(0) ""
}
*/
$string = ',g,6,4,3,f,32,a,';
$array = explode(',', $string);
$numericOnlyArray = array_filter($array,'is_numeric');
var_dump($numericOnlyArray);
/*
result:
array(4) {
[2]=>
string(1) "6"
[3]=>
string(1) "4"
[4]=>
string(1) "3"
[6]=>
string(2) "32"
}
*/
$string = ',g,6,4,3,f,32,a,';
$array = explode(',', $string);
$result = array_map('intval', array_filter($array, 'is_numeric'));
var_dump($result);
/*
result:
array(4) {
[2]=>
int(6)
[3]=>
int(4)
[4]=>
int(3)
[6]=>
int(32)
}
}
*/
return array_map('intval', explode(",", '1,2,3,4,5,6,7,8,9'));
explode(",",'1,2,3,4,5,6,7,8,9');
http://www.php.net/manual/en/function.explode.php
You can use http://pl.php.net/manual/en/function.explode.php