Understanding PHP sort() Function: Usage, Parameters, and Examples
This article explains how PHP's sort() function works for array sorting, demonstrates basic usage, descending order with rsort(), various sorting flags, and related functions like asort() and arsort(), providing code examples and important considerations for developers.
PHP is a widely used programming language for web development, and its sort() function is a powerful tool for sorting arrays. This article introduces the usage of sort() and related considerations.
Basic usage : sort() takes a single argument—the array to be sorted. Example:
<code>$fruits = array("apple", "banana", "orange");
sort($fruits);
print_r($fruits);
</code>The output shows the array sorted alphabetically in ascending order.
Descending order : Use rsort() to sort in descending order. Example:
<code>$numbers = array(4, 2, 6, 1, 3);
rsort($numbers);
print_r($numbers);
</code>The result is the array sorted from highest to lowest.
Sorting flags : sort() can accept a second parameter to specify different sorting behaviors, such as SORT_REGULAR , SORT_NUMERIC , SORT_STRING , SORT_LOCALE_STRING , SORT_NATURAL , and SORT_FLAG_CASE . Example using SORT_STRING (case‑insensitive string sorting):
<code>$fruits = array("apple", "Banana", "orange", "Pineapple");
sort($fruits, SORT_STRING);
print_r($fruits);
</code>This sorts the strings alphabetically without considering case.
Preserving keys : sort() modifies the original array and discards key associations. To keep keys, use asort() (ascending) or arsort() (descending). Example:
<code>$fruits = array("apple" => 2, "banana" => 1, "orange" => 3);
asort($fruits);
print_r($fruits);
</code>The output shows the array sorted by values while retaining the original keys.
Additional notes : sort() works only on arrays, sorting values only. For key‑based sorting, use ksort() or krsort() . Remember that sort() changes the original array; if you need the original order, copy the array first.
Conclusion : The sort() function is a versatile tool for array sorting in PHP. By understanding its parameters and related functions like asort() and arsort() , developers can efficiently sort data while preserving necessary information.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.