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//from  w  ww .  j a  v a2s.  c  o m
    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/*from w ww  .  java2 s  . c  o  m*/
    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/*from   ww w . ja v  a  2  s. c o m*/
    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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions