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.

php Courses
php Courses
php Courses
Using PHP sort() Function to Sort Arrays in Ascending Order

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): bool

Parameters: $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.

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.

algorithmPHPArraysort
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.