Using PHP sort() Function to Sort Arrays in Ascending Order
This article explains how to use PHP's built-in sort() function to sort arrays in ascending order, covering syntax, parameters, return values, and practical examples for both string and numeric arrays, including code snippets and output demonstrations.
In PHP, the built‑in sort function provides a simple way to sort an array in ascending order.
The function signature is:
sort(array &$array, int $sort_flags = SORT_REGULAR): boolParameters: $array: the array to be sorted (required). $sort_flags: optional flag that determines the sorting behavior; default is SORT_REGULAR. Other options include SORT_NUMERIC and SORT_STRING.
The function returns true on success, false otherwise.
Example for sorting strings:
<?php
$fruits = array("apple", "orange", "banana", "grape");
sort($fruits);
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
?>Output: apple banana grape orange Example for sorting numbers with SORT_NUMERIC:
<?php
$numbers = array(2, 30, 5, 10, 1);
sort($numbers, SORT_NUMERIC);
foreach ($numbers as $number) {
echo $number . " ";
}
?>Output: 1 2 5 10 30 Note that sort modifies the original array in place and does not return a new sorted array; you can also specify different sorting flags to meet various needs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
