- PHP

How to sort array in PHP without a function

To build your own array sorting function, compare each element of the array with all other elements.

We can achieve this by making a loop inside another loop.

  • Loop through all the array elements with foreach().
  • Loop through all elements inside every foreach() iteration with for() and compare the current element with all other elements.
  • If the current element is greater than the next value, swap their places.
<?php

foreach($array as $val) {
   for ($i=0; $i < count($array) - 1; $i++) { 
       if($array[$i] > $array[$i + 1]) {
            // swap these two array elements
            list($array[$i + 1], $array[$i]) = array($array[$i], $array[$i + 1]);
        }      
   }
}

?>

Example:

Sort an array without sort() function. Use the custom code to compare all the array data with loops.

<?php

$numbers = array(500, 2, 200, 999, 12, 7, 75, 150, 30, 8, 125);


foreach($numbers as $num) {
   for ($i=0; $i < count($numbers) - 1; $i++) { 
       if($numbers[$i] > $numbers[$i + 1]) {
            list($numbers[$i + 1], $numbers[$i]) = array($numbers[$i], $numbers[$i + 1]);
        }      
   }
}

print_r($numbers);

?>

Output:

Array ( [0] => 2 [1] => 7 [2] => 8 [3] => 12 [4] => 30 [5] => 75 [6] => 125 [7] => 150 [8] => 200 [9] => 500 [10] => 999 )