PHP: Sorting an array

Array can be sorted easily using the sort function.

<?php
 
$gift = array("TV","car","aeroplane", "iPad", "iPhone", "PS4"); 

echo "Before Sorting:\n";
echo "$gift[0] $gift[1] $gift[2] $gift[3] $gift[4] $gift[5]";


sort($gift);
echo "\n\n";
echo "After sorting:\n";
echo "$gift[0] $gift[1] $gift[2] $gift[3] $gift[4] $gift[5]";


?>

Another more elegant way of printing out the array is to use a for loop:

<?php
 
$gift = array("TV","car","aeroplane", "iPad", "iPhone", "PS4"); 

echo "Before Sorting:\n";
echo "$gift[0] $gift[1] $gift[2] $gift[3] $gift[4] $gift[5]";


sort($gift);

echo "\n\n";
for ($i=0; $i <= 5; $i++)
   {
    echo "$gift[$i]\n"; 
   }
?>

Series Navigation<< PHP: Array count
PHP: Associative array >>