PHP array sorting

Question

Answers ( 1 )

    0
    2024-01-11T18:05:19+00:00

    PHP offers various functions for sorting arrays, each serving different purposes. Here are some of the most commonly used PHP array sorting functions along with examples:

    1. sort() - Sorts an array in ascending order. This function reassigns the keys, so the array will have numeric keys starting from 0.

      $array = array("orange", "apple", "banana");
      sort($array);
      print_r($array);
      
    2. rsort() - Sorts an array in descending order, similar to sort() but in reverse.

      $array = array("orange", "apple", "banana");
      rsort($array);
      print_r($array);
      
    3. asort() - Sorts an associative array in ascending order according to the value. It preserves the keys.

      $array = array("a" => "orange", "b" => "apple", "c" => "banana");
      asort($array);
      print_r($array);
      
    4. arsort() - Sorts an associative array in descending order according to the value. It also preserves keys.

      $array = array("a" => "orange", "b" => "apple", "c" => "banana");
      arsort($array);
      print_r($array);
      
    5. ksort() - Sorts an associative array in ascending order according to the key.

      $array = array("c" => "banana", "a" => "orange", "b" => "apple");
      ksort($array);
      print_r($array);
      
    6. krsort() - Sorts an associative array in descending order according to the key.

      $array = array("c" => "banana", "a" => "orange", "b" => "apple");
      krsort($array);
      print_r($array);
      
    7. usort() - Sorts an array by values using a user-defined comparison function.

      function compare($a, $b) {
          if ($a == $b) {
              return 0;
          }
          return ($a < $b) ? -1 : 1;
      }
      
      $array = array(3, 2, 5, 6, 1);
      usort($array, "compare");
      print_r($array);
      
    8. uasort() - Sorts an array with a user-defined comparison function and maintains index association.

      // Same compare function as before
      $array = array("a" => 3, "b" => 2, "c" => 5);
      uasort($array, "compare");
      print_r($array);
      
    9. uksort() - Sorts an array by keys using a user-defined comparison function.

      // Same compare function as before
      $array = array("c" => 3, "a" => 2, "b" => 5);
      uksort($array, "compare");
      print_r($array);
      
    10. array_multisort() - Can be used to sort multiple arrays at once, or a multi-dimensional array by one or more dimensions.

    Each of these functions serves a specific purpose depending on the type of array and the desired sorting behavior. Remember that these functions modify the original array, except usort(), uasort(), and uksort(), which work with a user-defined comparison function and are therefore more flexible.

Leave an answer