PHP - Function array_reduce()


Advertisements


Syntax

array_reduce ( $array, callback $function [, int $initial] );

Definition and Usage

This function applies iteratively the function function to the elements of the array, so as to reduce the array to a single value. If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty. If the array is empty and initial is not passed.

Parameters

Parameter Description
array Required. Specifies an array.
function Required. Callback function.
initial Optional. Specifies the initial value to send to the function.

Return Values

Returns a reduced array.

Example

Try out following example −

<?php
   function call_back_function($v1,$v2) 
   {
      return $v1 . "-" . $v2;
   }
	
   $array=array("a"=>"banana","b"=>"apple","c"=>"orange");
   
   print_r(array_reduce($array, call_back_function));
   print_r("<br />");
   print_r(array_reduce($array, call_back_function, 10));
?> 

This will produce the following result −

-banana-apple-orange
10-banana-apple-orange

php_function_reference.htm