Hướng dẫn
Quảng cáo

Hàm array_reduce() trong PHP

Hướng dẫn cách sử dụng hàm array_reduce() về mảng trong lập trình PHP

Tác dụng của hàm array_reduce()

The array_reduce() function iteratively reduce the array to a single value using a callback function.

It basically applies a callback function to each element of the array to build a single value.

The following table summarizes the technical details of this function.

Return Value: Returns the resulting value.
Changelog: Since PHP 5.3.0, the initial parameter accepts multiple types or mixed (but not necessarily all). Previously, only integers are allowed.
Version: PHP 4.0.5+

Syntax

The basic syntax of the array_reduce() function is given with:

array_reduce(array, callback, initial);

The following example shows the array_reduce() function in action.

<?php
// Defining a callback function
function sum($carry, $item){
    $carry += $item;
    return $carry;
}

// Sample array
$numbers = array(1, 2, 3, 4, 5);
var_dump(array_reduce($numbers, "sum")); // int(15)
?>

Note: The callback function has two arguments carry and item: the first one holds the value returned by the previous iteration, and the second one is the current array element.


Parameters

The array_reduce() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
callback Required. Specifies the name of the callback function.
initial Optional. Specifies the value to be used at the beginning of the process.

More Examples

Here're some more examples showing how array_reduce() function actually works:

The following example will calculate the multiplication of array values. Since we've also specified an initial value, so the resulting value will be 1200 (because of: 10*1*2*3*4*5).

<?php
// Defining a callback function
function multiply($carry, $item){
    $carry *= $item;
    return $carry;
}

// Sample array
$numbers = array(1, 2, 3, 4, 5);
var_dump(array_reduce($numbers, "multiply", 10)); // int(1200)
?>

If the array is empty the initial value will be used as a final result, as shown here.

<?php
// Defining a callback function
function sum($carry, $item){
    $carry += $item;
    return $carry;
}

// Sample array
$empty = array();
var_dump(array_reduce($empty, "sum", "No data to reduce")); // string(17)
?>

If the array is empty and initial is not passed, the array_reduce() function returns NULL.

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements