Compare colors

Measure perceptual distance, check WCAG contrast, test equality.

With the same interface everywhere, any two colors can be measured against each other. Three questions cover most real work: how far apart, how readable, how equal.

Distance

Color::distance() scores how different two colors look: 0 is identical, small values are barely distinguishable neighbors:

use PhpColor\Color\Color;

$blue = Color::parse('#3b82f6');
$rose = Color::parse('#f43f5e');

Color::distance($blue, $rose);
// 43.16
use PhpColor\Color\Color; $blue = Color::parse('#3b82f6'); $rose = Color::parse('#f43f5e'); Color::distance($blue, $rose); // 43.16

$blue
$rose -- distance 43.16

Use it to dedupe a palette, find the closest named color, or catch two brand colors that sit too close to tell apart.

Contrast

Color::contrast() returns the WCAG 2.x ratio, the number accessibility guidelines are written in:

Color::contrast($blue, Color::white());
// 3.68 -- AA for large text only

Color::contrast($blue, Color::black());
// 5.71 -- AA for body text
Color::contrast($blue, Color::white()); // 3.68 -- AA for large text only Color::contrast($blue, Color::black()); // 5.71 -- AA for body text

vs white: 3.68
$blue
vs black: 5.71

The same blue that fails on white passes on black. Checking both directions before shipping a palette is a one-liner.

Equality

equals() compares resolved color values, not syntax:

$blue->equals(Color::parse('rgb(59 130 246)'));
// true -- same color, different notation
$blue->equals(Color::parse('rgb(59 130 246)')); // true -- same color, different notation

Go deeper: Contrast, distance, and color vision covers AA and AAA levels, APCA, and vision simulation.

Distance, WCAG contrast, and equality cover the comparisons in this tour. Time to build with them.