PHP array_reduce() Function
In this chapter you will learn:
- Definition for PHP array_reduce() Function
- Syntax for PHP array_reduce() Function
- Parameter for PHP array_reduce() Function
- Example - Reduce an array
- Example - Send initial value
- Example - return the sum
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
Parameter | Is Required | Description |
---|---|---|
array | Required. | Specifies an array |
myfunction | Required. | Name of the function |
initial | Optional. | Initial value to send to the function |
Example
<?php// j a va2s . com
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/* java2s. 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/*j a 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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_replace() Function
- Syntax for PHP array_replace() Function
- Parameter for PHP array_replace() Function
- Example - Replaces the values of the first array with the values
- Example for PHP array_replace() Function
- Example for If a key exists in array2 and not in array1
- Example - Using three arrays - the last array ($a3) will overwrite the previous ones ($a1 and $a2)
- Example - Using numeric keys - If a key exists in array2 and not in array1
Home » PHP Tutorial » PHP Array Functions