To sort on one column of values, a combination of array_column()
and array_multisort()
is one sensible way. Demo
array_multisort(array_column($array, 'count'), $array);
Or only call upon usort()
with the spaceship operator to perform less iterating in this scenario. Demo
usort($array, fn($a, $b) => $a->count <=> $b->count);
Notice that although the count values are cast as string type values in the input array, both sorting functions will correctly sort the values numerically instead of alphabetizing them (erroneously putting 23420
before 420
). This is a reliable default feature.
Even if you are variably declaring the column to sort on, both approaches allow the variable to be used without any addition techniques.
Multisort Demo with variable
$property = 'count';
array_multisort(array_column($array, $property), $array);
Usort Demo with variable
$property = 'count';
usort($array, fn($a, $b) => $a->$property <=> $b->$property);
Both native sorting functions modify by reference, so do not try to access the sorted array by their return value.
array_multisort()
's default sorting direction is ascending, so it is of no benefit to explicitly use the SORT_ASC
between the two array parameters. If descending sorting is desired, write SORT_DESC
between the two arrays (as the second parameter).
usort()
will sort ascending when the custom function body puts $a
data on the left side of the spaceship operator and $b
data on the right side. For sorting in a descending direction, just write $b
data on the left and $a
data on the right.
Both approaches are capable of receiving multiple sorting rules, but because this question only asks to sort on a single column, that guidance is inappropriate here.
It will be less efficient to call a function (like strcmp()
) on every iteration while sorting. This is no longer best practice. Neither is using a two-way comparison (like >
or <
) to return a boolean outcome. A three-way comparison is expected from usort()
.
For sorting data with multiple rules/columns/properties, this answer gives good guidance.