Anshu Shekhar Anshu Shekhar - 1 year ago 145
PHP Question

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

i cannot understand what is the use of


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.


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

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