I have the following code that case-insensitively groups associative elements in a flat array and sums the related values, but I don't really understand how it works.
function add_array_vals($arr) {
$sums = [];
foreach ( $arr as $key => $val ) {
$key = strtoupper($key);
if ( !isset($sums[$key]) ) {
$sums[$key] = 0;
}
$sums[$key] = ( $sums[$key] + $val );
}
return $sums;
}
$array = ['KEY' => 5, 'TEST' => 3, 'Test' => 10, 'Key'=> 2];
$sums = add_array_vals($array);
var_dump($sums);
//Outputs
// KEY => int(7)
// TEST => int(13)
I have problem in two portion of above code one is:
if ( !isset($sums[$key]) ) {
$sums[$key] = 0;
}
another is:
$sums[$key] = ( $sums[$key] + $val );
In this portion, how does it identify the same key of array to sum them (because keys position is dynamic)?
if ( !isset($sums[$key]) ) { $sums[$key] = 0; }
$sums
starts as an empty array, but we're trying to add numbers to it. If we try to add a number to $sums[$key]
that isn't initialized yet, we'll get an error, so we initialize it by setting it at zero the first time we encounter it.
$sums[$key] = ( $sums[$key] + $val );
This is the second part of the previous line. $sums[$key]
is at this point either zero, thanks to the previous line, or an integer, because we've encountered it before in the loop.
The $key
in $sums[$key]
is going to be either 'TEST' or 'KEY' in this code.