PrimitiveType

PHP: sorting arrays

PHP providers a number of functions for sorting arrays. Below are simple snippets that demonstrate sorting arrays with the functions sort(), asort() and rsort().

// Sort an array of numbers using sort() (you can mix number types) $myArray = array(3, 1, 2.2, 5, 4.6); sort($myArray); // 0 => 1, 1 => 2.2, 2 => 3, 3 => 4.4, 4 => 5 // Sort an array of strings using sort() $myArray = array('b', 'c', 'e', 'a', 'd'); sort($myArray); // 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e' // Sort an array of mixed case strings $myArray = array('b', 'C', 'e', 'a', 'D'); sort($myArray); // upper case letters appear first: 0 => 'C', 1 => 'D', 2 => 'a', 3 => 'b', 4 => 'e' // As of PHP 5.4 you can specify extra flags to make sort() case-insensitive $myArray = array('b', 'C', 'e', 'a', 'D'); sort($myArray, SORT_STRING | SORT_FLAG_CASE); // 0 => 'a', 1 => 'b', 2 => 'C', 3 => 'D', 4 => 'e' // sort() removes array keys and creates new zero-based ones $myArray = array(2 => 'b', 3 => 'c', 5 => 'e', 1 => 'a', 4 => 'd'); sort($myArray); // 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e' // asort() preservers the original keys $myArray = array(2 => 'b', 3 => 'c', 5 => 'e', 1 => 'a', 4 => 'd'); asort($myArray); // 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e' // Reverse sort an array of strings using rsort() $myArray = array('b', 'c', 'e', 'a', 'd'); rsort($myArray); // 0 => 'e', 1 => 'd', 2 => 'c', 3 => 'b', 4 => 'a'