array_reduce() function in PHP


The array_reduce() function returns an array as a string, using a user-defined function.

Syntax

array_reduce(arr, custom_func, initial)

Parameters

  • arr − The array. Required.
  • custom_func − The name of the user-defined function. Required.
  • initial − Initial value to be sent to the function. Optional.

Return

The array_reduce() function returns the resulting value. It returns NULL, if the array is an empty array and initial isn’t passed.

Example

The following is an example −

 Live Demo

<?php
function display($a1,$a2) {
   return $a1 . " DEMO " . $a2;
}
$a = array("One","Two");
print_r(array_reduce($a,"display",2));
?>

Output

The following is the output −

2 DEMO One DEMO Two

Example

Let us see another example wherein the given array is reduced o the product of all the elements of the array −

 Live Demo

<?php
function display($a1,$a2) {
   return $a1 + $a2;
}
$arr = array(50, 100, 150, 200, 250);
print_r(array_reduce($arr,"display",500));
?>

Output

The following is the output −

1250

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

28 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements