Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_reduce()

Example

Pass the values of an array to a user-defined function and return a single string.

<?php
function myfunction($v1,$v2)
{
return $v1 . “-“ . $v2;
}
$a=array(“Dog”,“Cat”,“Horse”);
print_r(array_reduce($a,“myfunction”));
?>

Definition and Usage

The array_reduce() function passes the values of an array to a user-defined function and returns a single result.

Note: If the array is empty and no initial value is provided, the function returns NULL.

Syntax

array_reduce(array, myfunction, initial)

Parameter Values

 

 

Parameter

Description

array

Required. Defines an array.

myfunction

Required. Provides the name of the function.

initial

Optional. Defines the initial value to pass to the function

Technical Details

Return Value:

Optional. Defines the initial value to pass to the function.

PHP Version:

4.0.5+

PHP Changelog:

As of PHP 5.3.0, the initial parameter can accept multiple types (mixed). In versions prior to PHP 5.3.0, it only accepted integers.

More Examples

Example

With the initial value parameter:

<?php
function myfunction($v1,$v2)
{
return $v1 . “-“ . $v2;
}
$a=array(“Dog”,“Cat”,“Horse”);
print_r(array_reduce($a,“myfunction”,5));
?>

Example

Returning a total sum:

<?php
function myfunction($v1,$v2)
{
return $v1+$v2;
}
$a=array(10,15,20);
print_r(array_reduce($a,“myfunction”,5));
?>