Filter a color palette

Keep only the entries that satisfy a predicate while retaining their names and relative order.

Source ink paper accent
Filtered ink accent
kept: ink, accent
removed: paper

Select without renaming the survivors

The predicate removes paper. The returned named palette keeps the ink and accent keys in their original order.

Put the selection rule in one callback

filter() passes each color to your predicate and returns a new palette containing only the accepted entries.

<?php

use PhpColor\Color\ColorInterface;
use PhpColor\Color\Palette\ColorPalette;

$palette = ColorPalette::parse([
    'ink' => '#111827',
    'paper' => '#f8fafc',
    'accent' => '#7c3aed',
]);

$dark = $palette->filter(
    static fn (ColorInterface $color): bool => $color->isDark(),
);

foreach ($dark->toHex() as $name => $hex) {
    printf("%s %s\n", $name, $hex);
}

// ink #111827
// accent #7c3aed
use PhpColor\Color\ColorInterface; use PhpColor\Color\Palette\ColorPalette; $palette = ColorPalette::parse([ 'ink' => '#111827', 'paper' => '#f8fafc', 'accent' => '#7c3aed', ]); $dark = $palette->filter( static fn (ColorInterface $color): bool => $color->isDark(), ); foreach ($dark->toHex() as $name => $hex) { printf("%s %s\n", $name, $hex); } // ink #111827 // accent #7c3aed

The predicate owns the meaning

PHPColor preserves the collection structure, but your callback decides what belongs. Document thresholds and context when they matter.

NamesString keys survive for retained entries.
OrderRelative order among retained entries remains stable.
ImmutabilityThe source palette remains unchanged.
Empty resultA predicate can return a palette with no retained colors.

Choose a next step

Keep the entries that match your declared rule