-1

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
*/
?>
ilyasmht01
  • 14
  • 5
  • Alright, so, loop through and set the case to match, and add them up. `strtoupper()`/`strtolower()` I think... it's been awhile, not totally sure, but yes. – Brad Oct 30 '22 at 00:41
  • Already tried but no result because strtoupper or strtolower will convert the full key but my array keys can start with uppercase and the rest of characters are lower case. – ilyasmht01 Oct 30 '22 at 01:29
  • 1
    Yes, convert the whole key and compare. – Brad Oct 30 '22 at 01:43
  • Closely related: [Group multidimensional array by one column and sum the other column](https://stackoverflow.com/q/25521462/2943403) and [Php count duplicate elements in an array and concat of ids](https://stackoverflow.com/q/28657236/2943403); tangentially related: [How to ignore case sensitivity and count array values?](https://stackoverflow.com/q/56655007/2943403); topical: [php: Array keys case *insensitive* lookup?](https://stackoverflow.com/q/4240001/2943403) – mickmackusa Oct 30 '22 at 03:27

3 Answers3

2

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)
}
kmoser
  • 8,780
  • 3
  • 24
  • 40
1

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)
  • Evidentally, you didn't explain this answer well enough. https://stackoverflow.com/q/74258272/2943403 ¯\\_(ツ)_/¯ – mickmackusa Oct 31 '22 at 06:10
  • 1
    @mickmackusa not sure what is so confusing its the same as the accepted answer only difference is an if statement before the math but I've edited anyway. – Jamie Sayers Oct 31 '22 at 12:29
0

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)
?>
ilyasmht01
  • 14
  • 5
  • This will throw a notice: "PHP Notice: Trying to access array offset on value of type null" if the first "Key" is mixed case but the 2nd is "KEY" uppercase. – kmoser Oct 30 '22 at 01:47
  • Are you sure ? Because i tested the case you told me I put Key in first element of array and worked without error. + This is the same code as yours you just made the $key strtoupper as a variable $k . – ilyasmht01 Oct 30 '22 at 02:16
  • Try it with `$array = ['Key'=> 5,'TEST' => 3,'Test' => 10,'KEY'=> 2];` and you will get "PHP Notice: Undefined variable: final in test.php on line 7", "Notice: Undefined variable: final in test.php on line 7", and "Notice: Trying to access array offset on value of type null in test.php on line 7". If you don't see those warnings, then perhaps your version of PHP has them suppressed. I'm using 7.4.6. – kmoser Oct 30 '22 at 02:52
  • It works just fine. You can verify my code and your code is the same there is no difference so if you tried my code and there is an error in your PHP version then even your code will have the same problem. As I explained before you just made the strtoupper as a variable $k and I used it directly on the array. – ilyasmht01 Oct 30 '22 at 10:20