I found a related answer here. Using the colors from the fifth row of this color table, and the names from this "Name that color" website, and the algorithm from the above answer, I wrote the following script, hexcode-rounding.php:
<?php
function distance_3d($rgb_1, $rgb_2) {
return sqrt(pow($rgb_1[0] - $rgb_2[0], 2) +
pow($rgb_1[1] - $rgb_2[1], 2) +
pow($rgb_1[2] - $rgb_2[2], 2));
}
if (isset($_POST["hexcode"])) {
$hexcode = $_POST["hexcode"];
$r = hexdec(substr($hexcode, 0, 2));
$g = hexdec(substr($hexcode, 2, 2));
$b = hexdec(substr($hexcode, 4, 2));
$rgb = [$r, $g, $b];
$basic_colors = [
'black' => [0, 0, 0],
'white' => [255, 255, 255],
'red' => [255, 0, 0],
'orange' => [255, 128, 0],
'yellow' => [255, 255, 0],
'chartreuse' => [128, 255, 0],
'green' => [0, 255, 0],
'spring green' => [0, 255, 128],
'cyan' => [0, 255, 255],
'azure' => [0, 128, 255],
'blue' => [0, 0, 255],
];
foreach ($basic_colors as $color_name => $color_rgb) {
echo "<p>$color_name: " . distance_3d($rgb, $color_rgb) . "</p>";
}
} else {
?>
<form action="hexcode-rounding.php" method="post">
<p>Hex code: <input type="text" name="hexcode" /><br />
<p><input type="submit" value="Round!"></p>
</form>
<?php
}
It prints out a list showing how close the given color is to each "basic" color in three dimensional RGB space. The lowest value in the list is the one that color is closest to. Notably missing are purple, brown, and pink, but it wouldn't be hard to add those in.