Sort a numerical array in ascending order using PHP

Hey Guys,
In this PHP tutorial, you are going to learn about creating a program to sort a numerical array in ascending order using PHP.

Ascending order is a sorting method in which we arrange number starting from small to big one.

In PHP we have an inbuilt method to sort the numbers in their ascending order that is sort( ) method.

Program to sort a numerical array in ascending order :

To sort an array we use sort( ) method in PHP. By the use of this method, our array gets sorted in just fraction of seconds which would reduce our effort and time while compared manually arranging the array.

sort( ):

sort is a method inbuilt in PHP which is used to sort the numbers/alphabets in a sorted way(ascending order).

In our daily life, we had to deal with a lot of things in which we need to arrange them in a sorted way which would make the task easier.

ex: inbox messages, contacts etc.

Algorithm :

  1. First, create a variable to store the array.
  2. Now assign the numeric array to the variable.
  3. Then call the sort(variable_name) method
  4. Now write a simple code to print all the numbers of the given array.
  5. Your program to sort numbers is ready to close PHP tags and get executed.

Example:

let us assume we have an array with numbers 5,8,6,25,1,2. Now we have to arrange them in a sorted format then to do in seconds we can choose to write a simple PHP code. Code will be as follows.

<?php

//initializing and assigning value to variable
$num = array(5 , 8 , 6 , 25 , 1 , 2);

//implementation of sort method

sort($numbers);

//printing the array variables
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) 
{
    echo $numbers[$x];
    echo "<br>";
}
?>

Output:

//we would get a sorted list of numbers
1
2
5
6
8
25

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *