PHP Sorting Array Manually


In this topic we will see how can we sort an array manually.

Copy Fullscreen Close Fullscreen
<?php
  $array = [12,23,4,556,76,5756,76,65,765,7657,567,23];
  /*get array lebgth*/
  $count = count($array);

  echo '<pre>Before Soeting : ';
  print_r($array);

  for($i=0; $i<$count; $i++)
  {
    for($j=$i+1; $j<$count; $j++)
    {
      if($array[$i] > $array[$j])
      {
        /*swap values*/
        $temp = $array[$i];
        $array[$i] = $array[$j];
        $array[$j] = $temp;
      }
    }
  }

  echo 'After Sorting : ';
  print_r($array);
?>
Output
Before Soeting : Array
(
    [0] => 12
    [1] => 23
    [2] => 4
    [3] => 556
    [4] => 76
    [5] => 5756
    [6] => 76
    [7] => 65
    [8] => 765
    [9] => 7657
    [10] => 567
    [11] => 23
)
After Sorting : Array
(
    [0] => 4
    [1] => 12
    [2] => 23
    [3] => 23
    [4] => 65
    [5] => 76
    [6] => 76
    [7] => 556
    [8] => 567
    [9] => 765
    [10] => 5756
    [11] => 7657
)

Note* Mean while you can use predefined sort(array) method to sort an array.

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook