PHP array_reduce() Function

❮ PHP Array Reference

Example

Send the values in an array to a user-defined function and return a string:

<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction"));
?>
Try it Yourself »

Definition and Usage

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

Note: If the array is empty and initial is not passed, this function returns NULL.


Syntax

array_reduce(array, myfunction, initial)

Parameter Values

Parameter Description
array Required. Specifies an array
myfunction Required. Specifies the name of the function
initial Optional. Specifies the initial value to send to the function


Technical Details

Return Value: Returns the resulting value
PHP Version: 4.0.5+
PHP Changelog: As of PHP 5.3.0, the initial parameter accepts multiple types (mixed). Versions prior to PHP 5.3.0, only allowed integer.

More Examples

Example

With the initial parameter:

<?php
function myfunction($v1,$v2)
{
return $v1 . "-" . $v2;
}
$a=array("Dog","Cat","Horse");
print_r(array_reduce($a,"myfunction",5));
?>
Try it Yourself »

Example

Returning a sum:

<?php
function myfunction($v1,$v2)
{
return $v1+$v2;
}
$a=array(10,15,20);
print_r(array_reduce($a,"myfunction",5));
?>
Try it Yourself »

❮ PHP Array Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.