Using 'reduce' for summing objects property in array - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.

Name: Using 'reduce' for summing objects property in array fullscreencopydownloadembedprint


Your result can be seen below.

Result of php executing





Full code of Using 'reduce' for summing objects property in array.php

  1. <?php
  2. $commissionsArray = [
  3.   (object) [
  4.     'name' => 'jon',
  5.     'commission' => 5
  6.   ],
  7.   (object) [
  8.     'name' => 'smith',
  9.     'commission' => 1
  10.   ],
  11.   (object) [
  12.     'name' => 'philip',
  13.     'commission' => 8
  14.   ],
  15.  
  16. ];
  17.  
  18.  
  19.  
  20. $total = array_reduce($commissionsArray, function ($sum, $entry) {
  21.   $sum += $entry->commission;
  22.   return $sum;
  23. }, 0);
  24.  
  25. echo "Total: $total\n";
  26.  
File Description
  • Using 'reduce' for summing objects property in array
  • PHP Code
  • 22 Mar-2021
  • 367 Bytes
You can Share it: