Using PHP asort() Function for Array Sorting

This article explains the PHP asort() function, detailing its syntax, sorting flags, and providing multiple examples—including basic usage, numeric sorting, string sorting, and associative array sorting—to demonstrate how to sort arrays in ascending order while preserving key associations.

php Courses
php Courses
php Courses
Using PHP asort() Function for Array Sorting

In PHP programming, the asort() function is used to sort arrays in ascending order while maintaining index association.

The syntax is

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

, where $array is the array to sort and $sort_flags specifies the sorting type, defaulting to SORT_REGULAR.

Common sorting flags include SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING, SORT_NATURAL, and SORT_FLAG_CASE.

Basic usage example:

$fruits = array("apple", "orange", "banana", "cherry");
asort($fruits);
print_r($fruits);

The result shows the array sorted alphabetically with original indices preserved.

Numeric sorting example:

$numbers = array(10, 5, 8, 3, 2);
asort($numbers, SORT_NUMERIC);
print_r($numbers);

String sorting example:

$names = array("John", "Abbey", "Chris", "David");
asort($names, SORT_STRING);
print_r($names);

Associative array sorting example:

$prices = array("apple" => 10, "banana" => 5, "cherry" => 15, "orange" => 8);
asort($prices);
print_r($prices);

These examples demonstrate that asort() can sort both indexed and associative arrays without altering key‑value relationships.

In summary, asort() is a versatile PHP function for ascending array sorting while preserving index associations, suitable for various data types and sorting flags.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

asortarray-sorting
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.