Jump to: navigation, search

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


Navigation
Web
SQL
MISC
References