3

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.

Sainan
  • 1,274
  • 2
  • 19
  • 32
Anshu Shekhar
  • 105
  • 2
  • 10
  • `array_walk` recursively calls a function on each element of array. So basically `inval()` is called on every array element to get the integer value from that element. check here:-http://php.net/manual/en/function.intval.php and http://php.net/manual/en/function.array-walk.php.. you can understand more through this:- https://eval.in/657790 – Alive to die - Anant Oct 09 '16 at 16:38
  • you can read and run the example from http://php.net/manual/en/function.array-walk.php for to learn `array_walk` – Ashok Chandrapal Oct 09 '16 at 16:48

2 Answers2

9

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);
});
?>
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
0

PHP's array_walk function calls the specified function on every object on an array, so in the case array_walk($arr, 'intval'); you are converting every value in the array to an integer, because that's what the intval function does.

Sainan
  • 1,274
  • 2
  • 19
  • 32