This code snippet randomly generates pairs of colors that make text look best on the background color.
/**
* Retrieve a color set of random background color and text color.
* It is optimized for a text color with high readability according to the luminance of the background color.
*
* @param int $luminance (optional: Luminance as a branch point of light and darkness is in the range of 0 to 255; defaults to 127)
* @param string $light_text (optional: Specify text color in case of darkness background color; defaults to "#ffffff")
* @param string $dark_text (optional; Specify text color in case of lignt background color; defaults to "#101010")
*
* @return array $colorset (has keys of "bg" and "txt")
*/
function randColorSet( $luminance = 127, $light_text = '#ffffff', $dark_text = '#101010' ): array {
$rgb = [ 'r' => 0, 'g' => 0, 'b' => 0 ];
$colorset = [ 'bg' => '#', 'txt' => $light_text ];
foreach( $rgb as $_key => $_val ) {
$rgb[$_key] = mt_rand( 0, 255 );
$colorset['bg'] .= str_pad( dechex( $rgb[$_key] ), 2, '0', STR_PAD_LEFT );
}
$yuv = 0.299 * $rgb['r'] + 0.587 * $rgb['g'] + 0.114 * $rgb['b'];
if ( $yuv >= $luminance ) {
$colorset['txt'] = $dark_text;
}
return $colorset;
}
The follow is an execution results:
header('Content-Type: text/plain; charset=UTF-8');
$i = 0; do {
print_r( randColorSet() );
$i++;
} while ( $i < 10 );
/* results:
Array (
[bg] => #adc47c
[txt] => #101010
)
Array (
[bg] => #e169f6
[txt] => #101010
)
Array (
[bg] => #21111d
[txt] => #ffffff
)
Array (
[bg] => #8adec3
[txt] => #101010
)
Array (
[bg] => #ca44d0
[txt] => #ffffff
)
Array (
[bg] => #71e216
[txt] => #101010
)
Array (
[bg] => #2cc12e
[txt] => #101010
)
Array (
[bg] => #f583ba
[txt] => #101010
)
Array (
[bg] => #c63b6d
[txt] => #ffffff
)
Array (
[bg] => #462a06
[txt] => #ffffff
)
*/

By the way, I will introduce sample code that lists a large number of unique color sets as the attached image of this article.
<div style="display:flex;flex-wrap:wrap;font-family:monospace,serif;">
<?php
$i = 0;
$max_colors = 255;
$used_colors = [];
do {
$colorset = randColorSet( 138 );
if ( ! in_array( $colorset['bg'], $used_colors, true ) ) {
$used_colors[] = $colorset['bg'];
printf(
'<div style="width:4em;height:1.3em;padding:0.5em;background:%1$s;color:%2$s;text-align:center">%1$s</div>',
$colorset['bg'],
$colorset['txt']
);
$i++;
}
} while ( $i < $max_colors );
?>
</div>
I try variously, I thought that around 138 of the brightness breakpoints (= value of $luminance argument) that divide the contrast of the text is good.