Skip to content

Instantly share code, notes, and snippets.

@alexkingorg
Created March 22, 2012 13:44
Show Gist options
  • Save alexkingorg/2158428 to your computer and use it in GitHub Desktop.
Save alexkingorg/2158428 to your computer and use it in GitHub Desktop.
Sort colors from dark to light
<?php
function cf_sort_hex_colors($colors) {
$map = array(
'0' => 0,
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9,
'a' => 10,
'b' => 11,
'c' => 12,
'd' => 13,
'e' => 14,
'f' => 15,
);
$c = 0;
$sorted = array();
foreach ($colors as $color) {
$color = strtolower(str_replace('#', '', $color));
if (strlen($color) == 6) {
$condensed = '';
$i = 0;
foreach (preg_split('//', $color, -1, PREG_SPLIT_NO_EMPTY) as $char) {
if ($i % 2 == 0) {
$condensed .= $char;
}
$i++;
}
$color_str = $condensed;
}
$value = 0;
foreach (preg_split('//', $color_str, -1, PREG_SPLIT_NO_EMPTY) as $char) {
$value += intval($map[$char]);
}
$value = str_pad($value, 5, '0', STR_PAD_LEFT);
$sorted['_'.$value.$c] = '#'.$color;
$c++;
}
ksort($sorted);
return $sorted;
}
@xsyfrost
Copy link

xsyfrost commented May 30, 2018

Unfortunatly not really working for me.
I have written by my own ;)

function cf_sort_hex_colors($colors) {
        $sorted = [];
        foreach ($colors as $color) {
            if (strlen($color) == 6) {
                $key = "";
                for($i=0;$i<6;$i++)
                {
                    $key .= sprintf('%02d',$this->map[substr($color, $i, 1)]);
                }
                $sorted[$key] = $color;
            }
        }

        ksort($sorted);
        return array_values($sorted);
    }

The color array is that way : ['eeeeee','ffffff', ...]. If the color code are using # juste add (as seen in the upper example :
$color = strtolower(str_replace('#', '', $color)); at the line 10 of the function replace $sorted[$key] = $color; by $sorted[$key] = '#'.$color;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment