skip to Main Content

I have the following code that case-insensitively groups associative elements in a flat array and sums the related values, but I don’t really understand how it works.

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)

I have problem in two portion of above code
one is:

if ( !isset($sums[$key]) ) {
   $sums[$key] = 0;
}

another is:

$sums[$key] = ( $sums[$key] + $val );

In this portion, how does it identify the same key of array to sum them (because keys position is dynamic)?

3

Answers


  1. if ( !isset($sums[$key]) ) { $sums[$key] = 0; }
    

    This means that if key or test has no value, assign the value 0.

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

    The value of KEY will be 0.

    $sums[$key] = ( $sums[$key] + $val );
    

    The $sums[$key] is the sum of same elements. $sums[$key] + $val means add the previous sum value to the new element value.

    Login or Signup to reply.
  2. This code summing by uppercase keys group.

    First step: checked the key exists. If not exists then fill with initial zero value. This case occurs once for per key (base of group). It is necessary so that the key’s non-existence does not pose a problem in the next step.

    if ( !isset($sums[$key]) ) { $sums[$key] = 0; }

    Second step: adds the value to the existed key container:

    $sums[$key] = ( $sums[$key] + $val );

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search