Use a foreach
loop to loop through the array keys and values passed through the function, convert the keys to uppercase using strtoupper
.
Inside the loop I've used isset
to check if the key is stored inside the sums table before adding the value onto the key in the sums array to prevent any errors when trying to add values together. The use !
refers to false or in simplier terms "is not" so saying !isset is asking the code if that array key is not set. If it isn't set in the sums array then we add the key in with the value 0 then add the value on top of it. Once the loop is complete we then return the sums array which is then stored in the the $sums variable outside the function.
Outside add_array_vals function, you can then use another foreach
loop to access the values.
function add_array_vals($arr) {
// Start an empty count array
$sums = [];
foreach ( $arr as $key => $val ) {
// Convert the key to uppercase
$key = strtoupper($key);
// Check if the key is already set
//when false it well set the key with the value 0
if ( !isset($sums[$key]) ) {
$sums[$key] = 0;
}
// $sums[$key] targets the key inside the sums table
// Since it is stored above, add $val onto what is already there
$sums[$key] = ( $sums[$key] + $val );
}
return $sums;
}
$array = ['KEY' => 5, 'TEST' => 3, 'Test' => 10, 'Key'=> 2];
$sums = add_array_vals($array);
foreach ( $sums as $key => $sum ) {
echo "The count for ". $key ." is: ". $sum;
}
var_dump($sums);
//Outputs
// KEY => int(7)
// TEST => int(13)