array_reduce

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_reduceRéduit itérativement un tableau

Description

function array_reduce(array $array, callable $callback, mixed $initial = null): mixed

array_reduce() applique itérativement la fonction callback aux éléments du tableau array, de manière à réduire le tableau à une valeur simple.

Liste de paramètres

array

Le tableau d'entrée.

callback
function callback(mixed $carry, mixed $item): mixed
carry

Contient la valeur retournée de l'itération précédente ; dans le cas de la première itération, ce sera la valeur du paramètre initial.

item

Contient la valeur de l'itération courante.

initial

Si l'argument optionnel initial est disponible, il sera utilisé pour initialiser le processus, ou bien comme valeur finale si le tableau est vide.

Valeurs de retour

Retourne la valeur résultante.

Si le tableau est vide et le paramètre initial n'est pas passé, array_reduce() retourne null.

Historique

Version Description
8.0.0 Si callback attend un paramètre à être passé par référence, cette fonction émet désormais une E_WARNING.

Exemples

Exemple #1 Exemple avec array_reduce()

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

function product($carry, $item)
{
    $carry *= $item;
    return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "sum")); // int(15)
var_dump(array_reduce($a, "product", 10)); // int(1200), car : 10*1*2*3*4*5
var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce"
?>

Voir aussi

add a note

User Contributed Notes 17 notes

up
142
Hayley Watson
18 years ago
To make it clearer about what the two parameters of the callback are for, and what "reduce to a single value" actually means (using associative and commutative operators as examples may obscure this).

The first parameter to the callback is an accumulator where the result-in-progress is effectively assembled. If you supply an $initial value the accumulator starts out with that value, otherwise it starts out null.
The second parameter is where each value of the array is passed during each step of the reduction.
The return value of the callback becomes the new value of the accumulator. When the array is exhausted, array_reduce() returns accumulated value.

If you carried out the reduction by hand, you'd get something like the following lines, every one of which therefore producing the same result:
<?php
array_reduce(array(1,2,3,4), 'f',         99             );
array_reduce(array(2,3,4),   'f',       f(99,1)          );
array_reduce(array(3,4),     'f',     f(f(99,1),2)       );
array_reduce(array(4),       'f',   f(f(f(99,1),2),3)    );
array_reduce(array(),        'f', f(f(f(f(99,1),2),3),4) );
f(f(f(f(99,1),2),3),4)
?>

If you made function f($v,$w){return "f($v,$w)";} the last line would be the literal result.

A PHP implementation might therefore look something like this (less details like error checking and so on):
<?php
function array_reduce($array, $callback, $initial=null)
{
    $acc = $initial;
    foreach($array as $a)
        $acc = $callback($acc, $a);
    return $acc;
}
?>
up
75
directrix1 at gmail dot com
10 years ago
So, if you were wondering how to use this where key and value are passed in to the function. I've had success with the following (this example generates formatted html attributes from an associative array of attribute => value pairs):

<?php

    // Attribute List
    $attribs = [
        'name' => 'first_name',
        'value' => 'Edward'
    ];

    // Attribute string formatted for use inside HTML element
    $formatted_attribs = array_reduce(
        array_keys