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
*/
?>
CodePudding user response:
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.
$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)
}
CodePudding user response:
You can use a foreach
loop to loop through each array item, use isset
to set new counts when the key doesn't exist in the sums array. Convert the keys to the same case using strtolower
or strtoupper
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)
CodePudding user response:
I found an answer for this question :
<?php
$array = ['KEY'=> 5,'TEST' => 3,'Test' => 10,'Key'=> 2];
$final = array();
foreach($array as $key => $value){
$final[strtoupper($key)] = ($final[strtoupper($key)] ?? 0) $value;
}
print_r($final)
?>