I'm working on solving "A Very Big Sum" on HackerRank. The goal is to produce the sum of all the elements in an array, without using array_sum. For clarity my example code here is a little bit different than the code there.
This works:
$arr = array(
1000000001,
1000000002,
1000000003,
1000000004,
1000000005
);
$total = 0;
array_walk($arr, 'totalize');
echo '*' . $total;
function totalize( $arr_item ) {
global $total;
$total += $arr_item;
}
I'd like to avoid using a global so I can do things properly when using callback functions in the future. However, this doesn't work. I'll show the output after the code:
$arr = array(
1000000001,
1000000002,
1000000003,
1000000004,
1000000005
);
$total = 0;
array_walk($arr, 'totalize', $total);
echo '*' . $total;
function totalize( $arr_item, $key, &$total ) {
$total += $arr_item;
echo $arr_item . '.' . $key . '.' . $total . '<br />';
}
It gives this as the output:
1000000001.0.1000000001
1000000002.1.2000000003
1000000003.2.3000000006
1000000004.3.4000000010
1000000005.4.5000000015
*0
Why does the $total get added up correctly but then gets abandoned?
use()or just do a simple foreach loop to go through your array and sum the values together.use, butuse()for anonymous functions, there is a difference :)