Choose Oklab for perceptually smoother application gradients unless an existing system requires linear-light sRGB. Sampling and CSS serialization are separate: PHPColor can sample in one space without emitting a CSS interpolation clause.
Choose the interpolation space
PHPColor interpolates gradients in Oklab by default. This usually provides a smoother perceptual transition than sRGB-based interpolation. Select sRGB when you need linear-light interpolation derived from sRGB channels:
use PhpColor\Color\Gradient\Gradient;
use PhpColor\Color\Gradient\InterpolationSpace;
$gradient = Gradient::linear()
->from('#ff0000')
->to('#0000ff')
->in(InterpolationSpace::Srgb)
->build();
use PhpColor\Color\Gradient\Gradient;
use PhpColor\Color\Gradient\InterpolationSpace;
$gradient = Gradient::linear()
->from('#ff0000')
->to('#0000ff')
->in(InterpolationSpace::Srgb)
->build();
The supported interpolation values are InterpolationSpace::Oklab ('oklab') and InterpolationSpace::Srgb ('srgb'). Passing another string to in() causes the enum conversion to throw ValueError.
The selected space controls colors returned by interpolate(). PHPColor’s CSS serializer does not add a CSS in <color-space> interpolation clause to the gradient text.
Sample a color from a gradient
Call interpolate() with a fractional position:
use PhpColor\Color\Gradient\Gradient;
$gradient = Gradient::linear(90.0, '#ff0000', '#0000ff');
$quarter = $gradient->interpolate(0.25);
echo $quarter->toHex();
use PhpColor\Color\Gradient\Gradient;
$gradient = Gradient::linear(90.0, '#ff0000', '#0000ff');
$quarter = $gradient->interpolate(0.25);
echo $quarter->toHex();
PHPColor sorts stops by position for sampling, locates the surrounding pair, and mixes them in the gradient’s interpolation space. A position before the first stop returns the first color; a position after the last stop returns the last.
An empty gradient samples as black. A one-stop gradient always returns that stop’s color. In application code, requiring at least two stops is usually clearer than relying on either fallback.
Use sampling as evidence
Inspect intermediate positions, not only the endpoints. A midpoint often reveals unwanted hue travel, low-chroma regions, or gamut clipping that endpoint review misses.
Sampling returns concrete colors for server-side previews, generated assets, or token extraction. It does not prove that a browser will interpolate the serialized gradient in the same space, because the current serializer omits the CSS in <color-space> clause.
Continue with Interpolate a brand transition, Sample a scale at token positions, or Build and sample gradients.