Generate a stable color from a string

Derive the same readable-looking color for a username, tag, or other stable key.

Hash the string into a hue, then hold OKLCH lightness and chroma constant:

use PhpColor\Color\Color;

function colorFor(string $value): string
{
    $hue = crc32($value) % 360;

    return Color::oklch(0.65, 0.15, $hue)->toHex();
}

echo colorFor('alice');
use PhpColor\Color\Color; function colorFor(string $value): string { $hue = crc32($value) % 360; return Color::oklch(0.65, 0.15, $hue)->toHex(); } echo colorFor('alice');

The same input produces the same color without storing a lookup table. Fixed lightness and chroma keep a collection of generated colors more coherent than hashing directly to RGB.

This does not guarantee text contrast. When the color becomes a background, use Find accessible foregrounds to choose and verify its text color.