# Sorting Sizes

Hi all, probably a quick one, how can I order my sizes in the correct order from youngest to oldest. I’m using the sort function but it’s sorting exactly how I’m wanting. Any help is appreciated as always Hey dude, thanks for your reply. Could you give me a breif example of how this is done…I’m not quite following… Yes, uksort takes two arguments a reference to an array and a function name, for example uksort(\$a, “cmp”);

So, the function “cmp” takes two arguments. We’ll define one that will compare 2 strings by splitting them into units (months < years), and ranges:
(3-6 > 0-3).
How to split them?
Take the units using the function explode, as follows:
\$tmp=explode(’ ‘, \$arg);
If arg=‘0-3 months’, Now \$tmp=‘0-3’, and \$tmp=‘months’
Now, we’ll split \$tmp to get the range:
\$rng=explode(’-', \$tmp);
Now, \$rng=‘0’, and \$rng=‘3’.
\$rng is a number.

OK, you should apply this to both arguments.
The cmp(\$a, \$b) should return an integer. That integer is:
negative if \$a<\$b
zero if \$a==\$b
positive if \$a>\$b

``````
\$array = array(
'0-3 Months',
'3-4 Years',
'3-6 Months',
'5-6 Years',
'6-9 Months'
);

function weigh(\$a, \$b){

\$a = sscanf(\$a, '%d-%d %s');
\$b = sscanf(\$b, '%d-%d %s');

\$map = array(
'Years'   => 12,
'Months'  => 1
);

\$a = \$a * \$map[\$a];
\$b = \$b * \$map[\$b];

if(\$a === \$b){
return 0;
}

return \$a < \$b ? -1 : 1 ;
}

usort(\$array, 'weigh');

print_r(
\$array
);

/*
Array
(
 => 0-3 Months
 => 3-6 Months
 => 6-9 Months
 => 3-4 Years
 => 5-6 Years
)
*/

``````

Hey chaps, that has done the job beautifully. All working very well. Just need to try and get my head around how it all works (:

Why are you sorting at all?

I’m building an e-commerce site, think it’s eaiser to read if the sizes are in order. Not yet got to the Payment Gateway, dreading that. Unsure how tough it is to implement?