Current Location: Home> Function Categories> array_reduce

array_reduce

Iteratively simplify the array to a single value with a callback function
Name:array_reduce
Category:Array
Programming Language:php
One-line Description:Return an array as a string by using user-defined functions.

Definition and usage

array_reduce() function sends the value in the array to the user-defined function and returns a string.

Note: If the array is empty and no initial parameter is passed, the function returns NULL.

Example

Example 1

Send values ​​in the array to the 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

Example 2

Set initial parameters:

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

Try it yourself

Example 3

Returns the sum:

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

Try it yourself

Similar Functions
Popular Articles