Trying to sort the array below by memnum in ascending order, and I'm a bit confused which is better to use... usort or array_multisort? I was thinking usort because it's multidimensional? Does anyone have an example of this?
Array
(
[0] => Array
(
[memnum] => 3236467423
[mid] => 1104881300
[fname] => JOHN
[lname] => DOE
[add1] => OMITTED
[add2] =>
[city] => CHESTERFIELD
[state] => MI
[zip] => 48051
[age] => 50
)
[1] => Array
(
[memnum] => 3258467922
[mid] => 1105121457
[fname] => JANE
[lname] => DOE
[add1] => OMITTED
[add2] =>
[city] => CHESTERFIELD
[state] => MI
[zip] => 48051
[age] => 50
)
[2] => Array
(
[memnum] => 3237769108
[mid] => 1104489312
[fname] => BOB
[lname] => DOE
[add1] => OMITTED
[add2] =>
[city] => CHESTERFIELD
[state] => MI
[zip] => 48051
[age] => 50
)
)
Since this is the most prominent Google result on array_multisort vs usort, I'm going to reply even though it's 4 years old.
usort() is more concise and doesn't require extracting a column array to feed to array_multisort(). (It also does less than array_multisort.)
However, when I repeatedly tested it today on arrays of 20,000 and 10,000 representative data rows, usort() was 7-15x slower than array_multisort() when the column was random values of type int and the column was pre-extracted. That is as one might expect, since for every comparison you're comparing an entire php function call to optimized intrinsic code.
Using an anonymous function as in the previous reply gave a 30-35% improvement over passing usort() the name of a defined function. It was never better than 8x slower and usually worse than 10x slower. Often this won't matter, but when you start getting up into tenths of a second of CPU time just for sorting one array, it might. Extracting the column without array_column() on a pre-5.5 server never quite halved the differential at best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With