PHP array sum

Question

Answers ( 1 )

    0
    2024-01-11T18:05:22+00:00

    In PHP, you can sum the elements of an array using various methods. Here are the most common ones:

    1. Using array_sum() Function The array_sum() function is the simplest and most direct way to sum the values of an array. It works well with both numeric and associative arrays, but only sums the numeric values.

      $array = [1, 2, 3, 4, 5];
      $sum = array_sum($array);
      echo $sum; // Output: 15
      
    2. Using a Loop You can also sum the values using a loop, such as a foreach loop. This method is more versatile as you can add custom logic if needed.

      $array = [1, 2, 3, 4, 5];
      $sum = 0;
      foreach ($array as $value) {
          $sum += $value;
      }
      echo $sum; // Output: 15
      
    3. Using array_reduce() Function The array_reduce() function is another way to sum values, allowing for more custom behavior. It applies a user-supplied function to each element of the array.

      $array = [1, 2, 3, 4, 5];
      $sum = array_reduce($array, function($carry, $item) {
          return $carry + $item;
      }, 0);
      echo $sum; // Output: 15
      

    These methods are generally used for summing numeric arrays. For associative arrays or more complex data structures, you may need to modify the logic accordingly. For instance, if you have an associative array where you want to sum values of a specific key, you would iterate over the array and sum only the values associated with that key.

Leave an answer