Skip to content

Array Functions

PHP Sort methods

We can work out what the sort method does by how it is named

a k u r
associative - keep the array as an associative array key - sorts by the key user - takes a callable (defined by the PHP users) reverse

sort()

  • SORT_REGULAR

This is the default sort flag.

This does not change by type when sorting and is the equivelent of ==

  • SORT_NUMERIC

Loses the original keys. Sorts the values alphabetical first, then numerical

Sort by Numberic 3v4l

<?php
$array = [
    "2" => "abc",
    "ab" => "abc12",
    "lkT" => 2,
    45 => "test",
    "This" => "is this",
    false => "abc012",
    " " => 22.22,
    ];

print_r($array);
sort($array, SORT_NUMERIC);
print_r($array);
  • SORT_STRING

    Sorting by alphanumeric characters, after the value has been juggled. This type of sort will use the ASCII Character Table to order the characters given in the string. An interesting type juggle is from true to "1" on this sort see the following: Sort by String 3v4l

    <?php
    $arr = [
        "  ", // Spaces
        "?", // Special Character
        2, // Integer
        3.01, // Float
        "php", // Lower-case String
        "pHP", // Camel-case String
        "Hello", // Title-Case String
        "123", // String Number
        true, // Boolean
        ];
    sort($arr,SORT_STRING);
    var_dump($arr);
    

  • SORT_LOCALE_STRING

This is the same as SORT_STRING but uses the current locale.

  • SORT_NATURAL

Loses the original keys. Used in natural sort. (the more clever sorting what accounts for strings+numbers)

Sort by Numberic 3v4l

<?php
$array = [
    "2" => "abc",
    "ab" => "abc12",
    "lkT" => 2,
    45 => "test",
    "This" => "is this",
    false => "abc012",
    " " => 22.22,
    ];

print_r($array);
sort($array, SORT_NATURAL);
print_r($array);

  • SORT_FLAG_CASE

    This will flag the insensitve case on when combined with SORT_NATURAL or SORT_STRING options. To use this: | bitwise OR operator must be chained with one of the string sorting options.

    <?php
    $arr = [
        "  ", // Spaces
        "?", // Special Character
        2, // Integer
        3.01, // Float
        "php", // Lower-case String
        "pHP", // Camel-case String
        "Hello", // Title-Case String
        "123", // String Number
        true, // Boolean
        ];
    sort($arr, SORT_STRING | SORT_FLAG_CASE);
    var_dump($arr);
    
    Sort with case insensitive

asort()

asort acts the same as sort (sorting the values) but keeps the keys with the values.

$array = ['ray' => 33, 'amanda' => 19, 'julio' => '49'];
# Sort by age
asort($array, SORT_NUMERIC);

https://3v4l.org/ZMsV4

In this example we want to keep the names with ages, otherwise we won't know who is what age.

arsort()

Keeps the original keys. Sorts the array by values .The reverse of asort. The equivalent of sort with SORT_REGULAR. Arsort 3v4l

<?php
$array = [
    "2" => "abc",
    "ab" => "abc12",
    "lkT" => 2,
    45 => "test",
    "This" => "is this",
    false => "abc012",
    " " => 22.22,
    ];

print_r($array);
arsort($array);
print_r($array);

krsort()

Sort with Key Reverse

Here we have used sorting by string in addition to the original reverse by key. Php will convert the specified key if it is a float or string that can be changed into an integer and then perform the reverse key sort. And because false juggles to 0 and then the sort function is called in reverse for the keys we have the fifth entry last.

<?php
$arr = [
    1 => "one",
    "two" => "two",
    3.01 => "three",
    "4" => "four",
    false => "five",
    ];
krsort($arr, SORT_STRING);
var_dump($arr); 

ksort()

ksort acts the same as asort but sorts by the keys. We do not have to specify the a to keep associations as we a sorting by the key so it is assumed the array is associative.

$array = ['10:38' => 'Dale', '8:06' => 'Catalin', '09:30' => 'Sam'];
# Sort by arraival
ksort($array, SORT_NATURAL);

We are using the SORT_NATURAL flag so we dont ge caught out by the 0 in front of the time.

https://3v4l.org/Q5SJj

natcasesort()

Keeps original keys. Same sorting as natsort but case insensitive. Natcasesort 3v4l

<?php
$array = [
    "2" => "abc",
    "3" => "aBc",
    "65" => "Abc",
    "ab" => "abc12",
    "lkT" => 2,
    45 => "test",
    "This" => "is this",
    false => "abc012",
    " " => 22.22,
    ];

print_r($array);
natcasesort($array);
print_r($array);

natsort()

(Sort an array with natural sort)[https://3v4l.org/tJpet]

Natural sort will take into account the concurrent numbers within a string and use that logic to arrange when sorting.

<?php

$arr = [
    "php4",
    "php12",
    "php1",
    "php123",
    ];

sort($arr);
var_dump($arr);    

natsort($arr);
var_dump($arr);

rsort()

rsort is the same as sort but reverse. It does not preeseve keys.

$array = ['bananna', 'cranberry', 'apple'];
rsort($array, SORT_STRING);

uasort()

Keeps original keys. Lets the user define the sorting algorithm. Not recommended as it is very slow. Sorts by value. Uasort 3v4l

<?php
$array = [
    "2" => "abc",
    "3" => "aBc",
    "65" => "Abc",
    "ab" => "abc12",
    "lkT" => 2,
    45 => "test",
    "This" => "is this",
    false => "abc012",
    " " => 22.22,
    ];

print_r($array);
uasort($array, function ($x, $y){
    return $x >= $y;
});
print_r($array);

uksort()

(User defined key sorting)[https://3v4l.org/OTC4k]

This sort assigns new keys to the array in the new arranged order. We are using a callback function which selects two elements keys, and returning a value will change the position of the element. * Here we are first checking whether when compared (juggled values) the first element is larger than the second selected element. If so this then returns +1 or -1, and iterates through the array accordingly.

  • The second function carries out a string comparison for length eventually receiving the largest key length at the start and smallest at the end of the array.
    <?php
    
    $arr = [
       "89098"=> "one",
       "aaaa123" => "two",
       "9" => "three",
       5 => "four",
       "7!?2,,--" => "five",
        ];
    
    uksort($arr, function($a, $b){
        return $a > $b;
    });
    var_dump($arr);
    
    uksort($arr, function($a, $b){
        return strcmp($a, $b);
    });
    var_dump($arr);
    

usort()

usort sorts by a user defined function, you must pass in a callable which calculates the order.

$array = ['bananna', 'cranberry', 'apple'];
$fn = function ($a, $b) {
    if(strlen($a) > strlen($b)) {
        return 1;
    }
    return 0;
};
usort($array, $fn);

https://3v4l.org/qZr7g

Using callable can take a signifigant amount of time, consideration shouold be made when making the choice to use any of the u sorts.

array_multisort()

<?php

$arr = [
    [
        123,
        321,
        231,
    ],    
    [
        "abc",
        "bca",
        "cab",
    ],
    [
        0.9999,
        43.786,
        false,
    ],
    ];

array_multisort($arr[0], SORT_DESC, SORT_NUMERIC,
                $arr[1], SORT_STRING,
                $arr[2], SORT_ASC, SORT_NATURAL
                );

var_dump($arr);
  • Dale

array_multi_sort can be used to sort multiple arrays or a multidimensional array.

array_multi_sort has many different parameters meaning there are many use cases but can be difficult to understand.

Lets take two arrays which list an item of food and how tasty it is.

$pastry = ['shortcrust' => 8, 'choux' => 4, 'filo' => 5];
$fillings = ['beef' => 3, 'cream' => 8, 'green onions' => 5];

The index of the pastry is matched with the index of the fillings.

Lets say we want to find the tastiest food.

$pastry = ['shortcrust' => 8, 'choux' => 4, 'filo' => 5];
$fillings = ['beef' => 3, 'cream' => 8, 'green onions' => 5];
array_multisort($fillings, $pastry);
array_multisort($pastry, $fillings);

https://3v4l.org/haBV1 https://3v4l.org/XNPi3

The indexes are matched and the second array is the one sorted.

Lets you combine all the above sorting algorithms.

<?php
$array1 = [
    "3" => "aBc",
    "ab" => "abc12",
    "lkT" => 2,
    "65" => "Abc",
    45 => "test",
    "This" => "is this",
    "2" => "abc",
    false => "abc012",
    " " => 22.22,
    ];

$array2 = [
    "5" => "abc",
    "2" => "bca",
    "1" => "?",
    "33" => "he11o",
    ];

print_r($array1);
print_r($array2);

array_multisort($array1, SORT_ASC, SORT_NUMERIC,
                $array2, SORT_DESC, SORT_NATURAL
                );

print_r($array1);
print_r($array2);

shuffle()

Changes sort order, works by reference. Loses original keys.
shuffle 3v4l

<?php

$array = [
    "5" => "abc",
    "2" => "bca",
    "1" => "?",
    "33" => "he11o",
    ];

print_r($array);
shuffle($array);
print_r($array);