How to usenatsort() Function for Natural Sorting in PHP
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 )
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