Anshu Shekhar Anshu Shekhar - 2 months ago 13
PHP Question

sum of array in php which includes use of array_walk()

i cannot understand what is the use of

array_walk($arr,'intval');


which i have made comment. Either i use it or not it is printing the same value. So, what is the use of it? I'm newbie to php.

<?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;
?>

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);
});
?>