I'm trying to sort my array values by size but I have a problem. My array pulls out values that are different than the values of the "cmp" function used to sort. The code is this:
function cmp($a, $b)
{
$sizes = array(
"XXS" => 0,
"XS" => 1,
"S" => 2,
"M" => 3,
"L" => 4,
"XL" => 5,
"XXL" => 6,
);
$asize = $sizes[$a];
$bsize = $sizes[$b];
if ($asize == $bsize) {
return 0;
}
return ($asize > $bsize) ? 1 : -1;
}
$your_array = array("GL001_XXL", "GL001_L", "GL001_XXS", "GL001_S");
usort($your_array, "cmp");
When I try to run this code, it tells me "Undefined key".
How can I sort my array without errors?
As noted in the comments, if your pattern is truly
xxx_size
, you can just explode on the_
and grab the second item.The
<=>
can be used whenever you've got the "return 0, 1 or -1" pattern, too.Demo: https://3v4l.org/Dqfi6