Sorting an Array by Keys in PHP


How To Sort an Array by Keys in PHP?



Sorting an array by keys can be done by using the ksort() function. It will re-order all pairs of keys and values based on the alphanumeric order of the keys. Here is a PHP script on how to use ksort():

$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
print("Sorted by keys:\n");

This script will print:

Sorted by keys:
    [] => Basic
    [Two] => Java
    [Zero] => PHP
    [1] => Perl
    [3] => C+
    [4] => Pascal
    [5] => FORTRAN


Sorting an Array by Values in PHP

Retrieving All Values from an Array in PHP

PHP Built-in Functions for Arrays

⇑⇑ PHP Tutorials

2017-01-21, 1392👍, 0💬