www.www.zaachi.com » My Blog/Php » PHP array ordering

Array sorting is very simple, because PHP have plenty of implements sort functions. Problem incoming as late as case, when we want sort of method, which isn’t implements.
We have array like this:
Array ( [0] => a [1] => d [2] => cc [3] => c [4] => b [5] => aa [6] => ab )
If we want sort this array of descending sequence or of ascending sequence, we can use function like Sort (from lowest to highest) or USort (from highest to lowest). Along usage we have array like this:
Array ( [0] => d [1] => cc [2] => c [3] => b [4] => ab [5] => aa [6] => a )
But I needed this array sort according to string of length. So I will have in the first place shortest string.
This problem solve function USort (Sort an array by values using a user-defined comparison function). In this function we can use self function to ordering.
Function for my problem will look like this:
function usort_array($a, $b)
{
if ($a === $b)
return 0;
if( strlen( $a ) === strlen( $b ) )
return ($a < $b) ? -1 : 1;
else
return ( strlen( $a ) < strlen( $b ) ? -1 : 1 );
}
And we will use it now:
$a = array('a', 'd', 'cc', 'c', 'b', 'aa', 'ab');
usort($a, "usort_array");
print_r( $a );
Output will be look like this:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => aa [5] => ab [6] => cc )
