Core PHP

Simple Array Sorting

Often, we want to sort the elemments of an array. The program below uses the built-in PHP sorting function to sort and reverse sort an array of elements.

SortArray.php

<?php
  // Create an associative array
  $saTribesOfIsrael = array("Reuben", "Simeon", "Levi", "Judah", "Issachar",
    "Zebulun", "Dan", "Naphtali", "Gad", "Asher", "Joseph", "Benjamin");

  echo "<h1>Array Sorting Methods:</h1>";

  // Use a foreach loop to print each key with its value
  echo "<h3>Original Order:</h3>";
  foreach ($saTribesOfIsrael as $sKey => $sValue) {
    echo "{$sKey} => {$sValue}<br />";
  }
  echo "<br />";

  sort($saTribesOfIsrael);

  // Use a foreach loop to print each key with its value
  echo "<h3>Alphabetical Sort Order:</h3>";
  foreach ($saTribesOfIsrael as $sKey => $sValue) {
    echo "{$sKey} => {$sValue}<br />";
  }
  echo "<br />";

  rsort($saTribesOfIsrael);

  // Use a foreach loop to print each key with its value
  echo "<h3>Reverse Alphabetical Sort Order:</h3>";
  foreach ($saTribesOfIsrael as $sKey => $sValue) {
    echo "{$sKey} => {$sValue}<br />";
  }
  echo "<br />";
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.