I have associative array.Operation of the below code is that it will sum all the array index's value which key is similar, but i did not understand how it operated.
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 it identify the same key of array to sum them because keys position is random.
It will be really helpful if anyone clarify it.
isset()
does and what+
does? Have you researched?