Anshu Shekhar Anshu Shekhar - 2 months ago 17
PHP Question

What does array_walk() do?

I don't get what

array_walk($arr, 'intval');
does, which I have commented out in the following code snippet:

<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
$arr_temp = fgets($handle);
$arr = explode(" ",$arr_temp);
//array_walk($arr,'intval');
$sum=0;
foreach($arr as $i)
{
$sum = $sum + $i;
}
echo $sum;
?>


If I use it or not does not seem to change the output.

Answer

The intention of it is that it should convert every item of $arr to integer.

But it does not do that!

Note that using array_walk with intval is inappropriate.

There are many examples on internet that suggest to use following code to safely escape arrays of integers:

<?php
array_walk($arr, 'intval'); // does nothing in PHP 5.3.3
?>

It works in some older PHP versions (5.2), but it is against specifications. Since intval() does not modify its arguments, but returns modified result, the code above has no effect on the array.

You can use following instead:

<?php
$arr = array_map('intval', $arr);
?>

Or if you insist on using array_walk:

<?php
array_walk($arr, function(&$e) { // note the reference (&)
   $e = intval($e);
});
?>