Anshu Shekhar Anshu Shekhar - 1 year ago 98
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:

$handle = fopen ("php://stdin","r");
$arr_temp = fgets($handle);
$arr = explode(" ",$arr_temp);
foreach($arr as $i)
$sum = $sum + $i;
echo $sum;

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

Answer Source

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:

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:

$arr = array_map('intval', $arr);

Or if you insist on using array_walk:

array_walk($arr, function(&$e) { // note the reference (&)
   $e = intval($e);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download