PHP Array Reduce

PHP Array Reduce

Last Updated on Feb 14, 2023

Array Reduce

Array reduce is a useful function that reduces the given array to a single value using a callback function. The callback function gets 2 arguments.

  1. carry holds the return value of the previous iteration
  2. item is the current item of the array

Let’s see an example 

$array = [1, 2, 3, 5, 10, 15];
$reduced = array_reduce($array, function ($carry, $item) {
   $carry += $item;
   return $carry;
});
echo $reduced;

Here I add all the values inside the array.

I should say that if you want to simply sum all the values or calculate the product of all the values you can simply use array_sum and array_product instead

echo array_sum($array);
// 36
echo array_product($array);
// 4500

But if you want to do something else, reduce is your friend.

Conclusion

Now you know about array reduce in PHP.

I recommend you to open a PHP files define arrays with different values try to reduce all of them to a single value with the help of array reduce function.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • array reduce in php
  • all the values of an array to a single value

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses