Php array reduce
From w3cyberlearnings
Contents |
PHP function array_reduce
This function generates a string from an array, and each array value sends to the user-defined function to return back result.
Syntax array_reduce
- array: array input
- function: user-defined function
- initial (optional): the first value to send to the function.
array_reduce(array, function, initial);
Example 1
<?php function makeup($v1, $v2) { return $v1 . '--' . $v2; } $name = array('Ella', 'Amelia', 'Liam', 'Melanie'); $list_str = array_reduce($name, "makeup"); echo $list_str; ?>
Output
--Ella--Amelia--Liam--Melanie
Example 2
<?php function makeup($v1, $v2) { return $v1 . '--' . $v2; } $name = array('Ella', 'Amelia', 'Liam', 'Melanie'); $list_str = array_reduce($name, "makeup",'Cute Name:'); echo $list_str; ?>
Output
Cute Name:--Ella--Amelia--Liam--Melanie
Example 3: to add up number
- Use array_reduce to add number together.
<?php function addup($v1, $v2) { return $v1 + $v2; } $score = array(40, 30, 25); $total = array_reduce($score, 'addup', 5); echo $total; ?>
Output
100
Example 4: to divide number
<?php function div($v1, $v2) { return $v1 / $v2; } $score = array(2, 2, 5); $total = array_reduce($score, 'div', 500); echo $total; ?>
Output
25
Related Links
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_ exists
- array_keys