PHP Program to Display Array Elements in Ascending Order of an Array

PHP Program to Display Array Elements in Ascending Order of an Array

  • PHP
  • 1 min read

Here is a PHP program to display the array elements in ascending order of an array.

<html>
<body>
<?php
$a=array(10,90,70,120,200,6);
$b=count($a);
for($i=0;$i<$b-1;$i=$i+1)
{
for($j=$i+1;$j<$b;$j=$j+1)
{
if($a[$i]>$a[$j])
{
$temp=$a[$i];
$a[$i]=$a[$j];
$a[$j]=$temp;
}
}
}
echo "The array elements are:-"."<br>";
for($i=0;$i<$b;$i=$i+1)
{
echo $a[$i]."<br>";
}
?>
</body>
</html>

Output: The array elements are:-

6
10
70
90
120
200

Explanation of the above program:

Firstly the first element will be compared with other elements and the lowest element will be placed as a first element. Next second lowest element will be placed in the second index position. This process will be continued for other elements, and we will get a sorted list.

We are repeatedly using steps through the list, compares values and swap them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

See also: