PHP

Partition Array Into Two Buckets

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Split an array into [matches, non-matches] using a predicate callback. Single pass, preserves order, returns two lists.
PHP
Raw
<?php
function partition(array $items, callable $predicate): array {
    $pass = $fail = [];
    foreach ($items as $item) {
        if ($predicate($item)) $pass[] = $item;
        else                   $fail[] = $item;
    }
    return [$pass, $fail];
}

[$evens, $odds] = partition([1,2,3,4,5,6], fn($n) => $n % 2 === 0);
print_r($evens);   // [2, 4, 6]
print_r($odds);    // [1, 3, 5]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.