Skip to content
Advertisement

How to sum php array that have same key but different sensitivity

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
*/
?>

Advertisement

Answer

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…”)

$array = ['KEY'=> 5, 'TEST' => 3,'Test' => 10,'Key'=> 2];

$array2 = [];
foreach ( $array as $k => $v ) {
    $k = strtoupper($k);
    $array2[ $k ] = $v + ( $array2[$k] ?? 0 );
}

var_dump($array2);

Result:

array(2) {
  ["KEY"]=>
  int(7)
  ["TEST"]=>
  int(13)
}
4 People found this is helpful
Advertisement