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 print this value it tells me "Undefined key".
How can I sort my array without errors?
2
Answers
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
I advise against using
usort()
for this task because this involves parsing both strings each iteration (which is more than N times).Instead, it will be more performant and very concise to use
array_multisort()
. Because your input strings appear to be consistently padded with zeros, you can simply parse the strings by grabbing the substring starting from the 6th character offset.Code: (Demo)
This approach will have the bonus effect of breaking ties (identical size values) by performing natural comparisons on the whole strings.