Sorting and Searching Arrays
Use sort, usort, array_search, and in_array.
Why Sort?
PHP provides a rich set of sorting and searching functions for arrays. Choose the right one based on whether you want to preserve keys, sort by value or key, or use a custom comparator.
sort() and rsort()
sort() sorts by value ascending (re-indexes); rsort() sorts descending:
<?php
$nums = [3, 1, 4, 1, 5, 9, 2, 6];
sort($nums);
print_r($nums); // [1, 1, 2, 3, 4, 5, 6, 9]
$letters = ['c', 'a', 'b'];
rsort($letters);
print_r($letters); // ['c', 'b', 'a']All lessons in this course
- Indexed and Associative Arrays
- Multidimensional Arrays
- Sorting and Searching Arrays
- Array Transformation Functions