Core PHP

User-defined Array Sorting

We can sort arrays according to user-specified methods by passing in a user-defined comparison function.

UserDefinedSort.php

<?php
  function CompareModulus19($iM, $iN) {
    $iM19 = ($iM % 19);
    $iN19 = ($iN % 19);
    if ($iM19 == $iN19) {
      return 0;
    }
    return ($iM19 < $iN19) ? -1 : 1;
  }

  // Create an array of numbers
  $saNumbers = array(109, 67, 38, 12, 90, 65, 42);

  echo "<h1>User-defined Sorting:</h1>";

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

  sort($saNumbers);

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

  usort($saNumbers, "CompareModulus19");

  // Use a foreach loop to print each key with its value
  echo "<h3>Modulus 19 Sort Order:</h3>";
  foreach ($saNumbers as $sKey => $sValue) {
    echo "{$sKey} => {$sValue} &Congruent; ".($sValue % 19)." (Mod 19)<br />";
  }
  echo "<br />";
?>
 

Output

 
 

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