OneBite.Dev - Coding blog in a bite size

Sort Items In Array By Asc In PHP

Code snippet for how to Sort Items In Array By Asc In PHP with sample and detail explanation

Sorting items in an array in ascending order is a crucial operation for many PHP web applications. This basic operation can assist in organizing data effectively and making the application more intuitive and interactive for the end-user.

Code snippet for Sorting Items in Array By Asc In PHP

Here is a simple code snippet that uses the sort() function in PHP to sort an array of items in ascending order:

<?php
    $numbers = array(4, 6, 2, 22, 11);
    sort($numbers);

    foreach($numbers as $number)
        echo $number . "<br>";
?>

After executing this code, the output on the browser will be:

2
4
6
11
22

Code Explanation for Sorting Items In An Array By Asc In PHP

Let’s break down the code and understand how everything works.

  1. An array named ‘$numbers’ is defined with some integer values. PHP arrays can hold many data types, such as numbers, strings, etc. In this case, the array is holding integer values.

     $numbers = array(4, 6, 2, 22, 11);
  2. Then, the built-in PHP function ‘sort()’ is used. The sort() function sorts the elements of the input array in low-to-high order—that is, in ascending order. It’s essential to know that the sort() function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

     sort($numbers);
  3. After sorting the array, a foreach loop is used to print out all the elements of the sorted array. In PHP, the foreach loop is used when we want to perform an action on every element in an array.

     foreach($numbers as $number)

    Here, ‘as’ is a keyword and ‘$number’ is a temporary variable which gets the value of each element of the array one by one.

  4. Inside the loop, we use the echo command to print out each item in the array, separately on a new line with the addition of
    (the HTML line break tag).

       echo $number . "<br>";

That’s how we sort items in an array using built-in PHP functions. Happy coding!

php