PHP Tutorial - PHP array_reduce() Function






Definition

The array_reduce() function sends the values in an array to a user-defined function, and returns a string.

Syntax

PHP array_reduce() Function has the following syntax.

array_reduce(array,myfunction,initial)

Parameter

ParameterIs RequiredDescription
arrayRequired.Specifies an array
myfunctionRequired.Name of the function
initialOptional.Initial value to send to the function

Example


<?php
    function myfunction($v1,$v2){
       return $v1 . "-" . $v2;
    }
    $a=array("A","B","C");
    print_r(array_reduce($a,"myfunction"));
?>

The code above generates the following result.





Example 2

With the initial parameter:


<?php
    function myfunction($v1,$v2){
       return $v1 . " vs " . $v2;
    }
    $a=array("PHP","Java","java2s.com");
    print_r(array_reduce($a,"myfunction",5));
?>

The code above generates the following result.

Example 3

Returning a sum:


<?php
    function myfunction($v1,$v2){
       return $v1+$v2;
    }
    $a=array(1,2,6);
    print_r(array_reduce($a,"myfunction",5));
?>

The code above generates the following result.