Skip to content

Instantly share code, notes, and snippets.

@doekenorg
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doekenorg/5564cf192a668fbaf100 to your computer and use it in GitHub Desktop.
Save doekenorg/5564cf192a668fbaf100 to your computer and use it in GitHub Desktop.
Sort array of sizes relative to amount of X's (XXS, S, M, L, XL, etc)
<?php
$sizes = array("XS", "L", "M", "S", "XXS", "XXL", "XXS", "M", "XXXXXL", "XL");
// Function doesn't handle (X+)M, because that would make no sense at all.
function sizeSort($cmp1, $cmp2)
{
$sort = array("S", "M", "L");
if (preg_match("/(^[X]*)([SML])$/is", $cmp1, $parts_1) && preg_match("/(^[X]*)([SML])$/is", $cmp2, $parts_2)) {
$weight_1 = array_search($parts_1[2], $sort);
$weight_2 = array_search($parts_2[2], $sort);
if ($weight_1 !== $weight_2) {
return ($weight_1 < $weight_2 ? -1 : 1);
}
$sub_weight_1 = strlen($parts_1[1]);
$sub_weight_2 = strlen($parts_2[1]);
if ($sub_weight_1 !== $sub_weight_2) {
if ($weight_1 > 1) {
//L so more X is higher
return ($sub_weight_1 > $sub_weight_2 ? 1 : -1);
} elseif ($weight_1 < 1) {
//S so more X is lower
return ($sub_weight_1 > $sub_weight_2 ? -1 : 1);
}
}
}
return 0; // same input
}
usort($sizes, "sizeSort");
//output : XXS, XXS, XS, S, M, M, L, XL, XXL, XXXXXL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment