Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
@johannesnagl

This comment has been minimized.

Copy link

@johannesnagl johannesnagl commented May 28, 2013

awesome! thx for your help on this one.

@megazalrock

This comment has been minimized.

Copy link

@megazalrock megazalrock commented Aug 23, 2013

nice ! You saved the day.

@xsyfrost

This comment has been minimized.

Copy link

@xsyfrost 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