stwhite - 6 months ago 17
PHP Question

# Sort MultiDimensional Array by Number Value with Zero Last

What I'm trying to do is sort a multidimensional array by a number but have any values equal to 0, to be at the end of the array.

This code works for sorting with 0's and single digits, but it seems to break when different numbers are added to it.

The output needs to be:
41,42,43,44,45,46,0,0,0

``````<?php

\$array = array(
array(
"position" => 41,
),
array(
"position" => 43,
),
array(
"position" => 42,
),
array(
"position" => 44,
),
array(
"position" => 45,
),
array(
"position" => 0,
),
array(
"position" => 0,
),
array(
"position" => 0,
),
array(
"position" => 46,
),
);
// Sort ascending
usort(\$array, 'sortByPosition');

// Show result
echo '<pre>';
print_r(\$array);

function sortByPosition(\$a, \$b) {
return \$a['position'] != 0 ? \$a['position'] - \$b['position'] : \$b['position'] - \$a['position'];
}
``````

Your comparison function is a bit off. I would do it like this:

``````function sortByPosition(\$a, \$b) {
if (\$a['position'] == \$b['position']) return 0;
if (\$a['position'] == 0) return 1;
if (\$b['position'] == 0) return -1;
return \$a['position'] > \$b['position'] ? 1 : -1;
}
``````
• First, if both positions are the same, return 0, regardless of whether either of them are zero.

• Second and third, if either of them are zero, that one should sort after the other (since it already would have returned if they were both zero).

• Fourth, neither are zero, so just compare the values normally.