Core PHP

Sorting Arrays by Keys and Values

When sorting associative arrays, we generally want to key the keys and values paired together and be able to sort based on either one. Key and value based sorting for associative arrays is demonstrated in the program below.

KeyValueSort.php

<?php
  // Create an associative array
  $saSacraments = array("Holy Orders"=>"Service", "Baptism"=>"Initiation", "Penance"=>"Healing",
    "Eucharist"=>"Initiation", "Marriage"=>"Service", "Annointing"=>"Healing",
    "Confirmation"=>"Initiation");

  echo "<h1>Key and Value Array Sorting:</h1>";

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

  asort($saSacraments);

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

  arsort($saSacraments);

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

  ksort($saSacraments);

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

  krsort($saSacraments);

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

Output

 
 

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