array_reduce() To Filter And Alter

By Rahul Chavan

<?php
$users = [
    [
        "id" => 1,
        "name" => "rahul",
        "premium" => true,
        "purchases" => ["apple", "banana", "carrot"],
        "price" => 22,
        ],
    [
        "id" => 2,
        "name" => "abhi",
        "premium" => false,
        "purchases" => ["apple", "banana", "carrot"],
        "price" => 22,
        ],
        [
        "id" => 3,
        "name" => "kavita",
        "premium" => true,
        "purchases" => ["apple", "banana", "carrot", "orange"],
        "price" => 30,
        ],
    ];

$premiumUsers = array_reduce(
    $users,
    function ($carry, $user) {
        if ($user['premium']) {
            $carry[] = [
                "name" => $user["name"],
                "purchases" => $user["purchases"],
                "price" => $user["price"] - 2
                ];
        }
        return $carry;
    },
    []
);

print_r($premiumUsers);

/**
 * Array
(
    [0] => Array
        (
            [name] => rahul
            [purchases] => Array
                (
                    [0] => apple
                    [1] => banana
                    [2] => carrot
                )

            [price] => 20
        )

    [1] => Array
        (
            [name] => kavita
            [purchases] => Array
                (
                    [0] => apple
                    [1] => banana
                    [2] => carrot
                    [3] => orange
                )

            [price] => 28
        )

)
 */

Using array_reduce() to create custom data structures goes beyond simple filtering.

array_reduce() might save a second loop. Although, it might also be quite slow, in particular for large arrays (10 millions+).

array_reduce() doesn’t provide keys when processing them.

See Also

PHP Features

Last updated: 14 July 2026