Table of contents Home page
// This function sorts numbers in ascending order, except that the odd numbers come before the even numbers function oddSort($a, $b) { if ($a % 2 != 0) // $a is odd { if ($b % 2 != 0) // $b is also odd { return $a < $b ? -1 : 1; } else // $a is odd and $b is even, so $a must come before $b { return -1; } } else // $a is even { if ($b % 2 != 0) // $a is even and $b is odd, so $b must come before $a { return 1; } else // $b is also even { return $a < $b ? -1 : 1; } } } $numbers = array(8, 6, -3, 7, 2, 9, -4, 0); if (usort($numbers, 'oddSort')) { echo 'Sorted: '; foreach ($numbers as $number) { echo "$number\n"; } } else { echo "Sort error\n"; }