Bifalgorithm post · Computer science one · Sorting
How can PHP arrays be sorted with sort() and usort()?
How can PHP arrays be sorted with sort() and usort()? (Computer science one · Sorting) — "PHP’s sort() function can be used to sort elements in ascending order…
Ideas in this flowchart
- PHP provides functions for sorting array elements.
- sort() sorts array elements in ascending order.
- It is useful for arrays containing numbers or strings.
- It does not work very well with mixed types or objects.
- String example: ("banana", "Apple", "zebra", "apple", "bananas") becomes ("Apple", "apple", "banana", "bananas", "zebra").
- Numeric example: (10, 8, 3, 12, 4, 42, 7, 108) becomes (3, 4, 7, 8, 10, 12, 42, 108).
- usort() is a more versatile user-defined sorting function.
- usort() accepts a comparator function that defines the element ordering.
- The comparator is passed as a string containing its function name.
- PHP function names are case insensitive, but matching the naming remains best practice.
- usort() can sort integers in descending order with cmpIntDesc.
- An array of Student instances can be sorted by name, ID, or GPA.
- Sorting by name uses studentByNameCmp.
- Sorting by ID uses studentIdCmp.
- Sorting by GPA uses studentGpaCmp.