当前位置:  首页>> 技术小册>> PHP合辑3-数组函数

PHP的此内建函数用于将数组元素减少为单个值,可以是浮点数,整数或字符串值。该函数使用用户定义回调函数来减少输入数组。

语法:

array_reduce(array,own_function,initial)

参数:

该函数采用三个参数,描述如下:

$array(必需):这是必需的参数,指的是我们需要从中减少的原始数组。

$own_function(必需):这也是必需的参数,指的是用于保存$array值的用户定义函数。

$initial(可选):这是可选的参数,指的是要发送给函数的值。

返回值:该函数返回减少后的结果。它可以是任何类型,包括int,float或string。

示例:

  1. Input : $array = (15, 120, 45, 78)
  2. $initial = 25
  3. own_function() takes two parameters and concatenates
  4. them with "and" as a separator in between
  5. Output : 25 and 15 and 120 and 45 and 78
  6. Input : $array = array(2, 4, 5);
  7. $initial = 1
  8. own_function() takes two parameters
  9. and multiplies them.
  10. Output : 40

在这个程序中,我们将看到如何将一个整数元素的数组减少到一个单独的字符串值。我们还传递了我们选择的初始元素。

  1. <?php
  2. // PHP function to illustrate the use of array_reduce()
  3. function own_function($element1, $element2)
  4. {
  5. return $element1 . " and " . $element2;
  6. }
  7. $array = array(15, 120, 45, 78);
  8. print_r(array_reduce($array, "own_function", "Initial"));
  9. ?>

output:

  1. Initial and 15 and 120 and 45 and 78

在下面的程序中,array_reduce使用own_function()将给定数组减少为数组中所有元素的乘积。

  1. <?php
  2. // PHP function to illustrate the use of array_reduce()
  3. function own_function($element1, $element2)
  4. {
  5. $element1 = $element1 * $element2;
  6. return $element1;
  7. }
  8. $array = array(2, 4, 5, 10, 100);
  9. print_r(array_reduce($array, "own_function", "2"));
  10. ?>

output:

  1. 80000