I want to sum the value of keys that are the same but in diffrent case.
Let’s say we have this array
<?php
$array = ['KEY'=> 5, ,'TEST' => 3,'Test' => 10,'Key'=> 2];
//---
a function to sum
//---
print_r($array);
/*
['KEY'] => 7,
['TEST'] => 13
*/
?>
3
Answers
I found an answer for this question :
Use a
foreach
loop to loop through the array keys and values passed through the function, convert the keys to uppercase usingstrtoupper
.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.Loop through the keys and values. Convert each key to uppercase. In a 2nd array, set the key/value to the sum of the current value in that array (or 0 if it doesn’t exist) plus the value you are up to in the loop.
I’m using the null coalescing operator
??
to determine whether the array key is set, and if not then use the value 0. (This prevents PHP from throwing a "Notice: Trying to access array offset on value of type null…")Result: