Using usort() function for Custom Sorting
For custom sorting, you can use usort() function and provide your own comparison function.
PHP
<?php $names = [ "John" , "Alice" , "Bob" , "Eve" , "Charlie" ]; usort( $names , function ( $a , $b ) { return strcmp ( $a , $b ); }); print_r( $names ); ?> |
Output
Array ( [0] => Alice [1] => Bob [2] => Charlie [3] => Eve [4] => John )
PHP Program to Sort Names in an Alphabetical Order
Sorting names in alphabetical order is a common task in programming. PHP provides several functions and methods to achieve this.
Examples:
Input: arr = ["Sourabh", "Anoop, "Harsh", "Alok", "Tanuj"]
Output: ["Alok", "Anoop", "Harsh", "Sourabh", "Tanuj"]
Input: arr = ["John", "Alice", "Bob", "Eve", "Charlie"] Output: ["Alice", "Bob", "Charlie", "Eve", "John"]
Table of Content
- Using sort() Function
- Using asort() Function for Associative Arrays
- Using natsort() Function for Natural Sorting
- Using usort() function for Custom Sorting