PHP Program to Sort Names in an Alphabetical Order
Last Updated :
02 Jan, 2024
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"]
Approach 1. Using sort() Function
The sort() function in PHP is used to sort an indexed array in ascending order.
PHP
<?php
$names = [ "John" , "Alice" , "Bob" , "Eve" , "Charlie" ];
sort( $names );
print_r( $names );
?>
|
Output
Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
[3] => Eve
[4] => John
)
Approach 2: Using asort() Function for Associative Arrays
If you have an associative array with keys and values, you can use asort() to sort the array by values while maintaining the key-value association.
PHP
<?php
$names = [
"John" => 30,
"Alice" => 25,
"Bob" => 35,
"Eve" => 28,
"Charlie" => 40
];
asort( $names );
print_r( $names );
?>
|
Output
Array
(
[Alice] => 25
[Eve] => 28
[John] => 30
[Bob] => 35
[Charlie] => 40
)
Approach 3: Using natsort() Function for Natural Sorting
If you have names with numbers, and you want a more natural order, you can use natsort() function.
PHP
<?php
$names = [
"John" => 30,
"Alice" => 25,
"Bob" => 35,
"Eve" => 28,
"Charlie" => 40
];
natsort( $names );
print_r( $names );
?>
|
Output
Array
(
[Alice] => 25
[Eve] => 28
[John] => 30
[Bob] => 35
[Charlie] => 40
)
Approach 4: 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
)
Share your thoughts in the comments
Please Login to comment...