Converting array of string to array of integers in PHP -
i followed leads in questions this , this.
i trying convert input stream of numbers array of integers. code should self explanatory.
$handle = fopen("php://stdin","r"); print("enter space separated numbers made array\n"); $numstream = fgets($handle); print("creating array : {$numstream}\n"); //using explode create arrays //now have array of strings $numarray = explode(" ", $numstream); var_dump($numarray); print(gettype($numarray[0])); print("\n"); array_walk($numarray, 'intval'); print(gettype($numarray[1])); print("\n"); var_dump($numarray); print_r($numarray);
i trying convert string array,
array_walk($numarray, 'intval')
the last 2 print blocks prints type of array element before , after conversion.
the output string in both cases
string string
i wonder going on here? possibly..
- the conversion wrong
- how type checked wrong
or possibly both.
adding complete input , output,
$ php arrays/arraystringtointeger.php enter space separated numbers made array 1 1 creating array : 1 1 array ( [0] => 1 [1] => 1 ) string string /home/ubuntu/workspace/basics/arrays/arraystringtointeger.php:22: array(2) { [0] => string(1) "1" [1] => string(2) "1 " } array ( [0] => 1 [1] => 1 )
you should use array_map
instead of array_walk
:
$numarray = array_map('intval', $numarray);
if still want use array_walk
- refer manual says:
if callback needs working actual values of array, specify first parameter of callback reference. then, changes made elements made in original array itself.
as intval
function doesn't work references need wrap in other logics, like:
array_walk($numarray, function(&$v){ $v = intval($v); }); // same @bizzybob solution)))
Comments
Post a Comment