Array functions [sorting elements]

Nico Anastasio
Apr 29 · 12 min read

Sorting array using functions

If you’ve followed this series on array functions until now I’m sure you’ve learned a lot.

If you haven’t (shame on you!) Here is a quick recap:

In the first chapter, we saw what an array is like, what syntax to use and what it is made for,

in the second chapter, we focused on the most used functions, or at least those deemed most popular,

in the third and last chapter published so far, we focused on element optimization, and we did it by reading about filtering functions.

In this chapter of the series, you will go to see another fundamental part concerning the arrays.

In this post, in fact, you will learn all about .

And you will do it in the fastest way possible, meaning, using functions present within the PHP core.

The core of PHP was written using C which is a lower level programming language, thus faster than PHP itself

The PHP language, in fact, provides several built-in functions written in a lower-level language which makes the execution of the scripts that you will write much faster,

Not to mention that the functions are there, ready for use, so why reinvent the wheels anyway?

sort()

let’s start with the most logical of functions when it comes to ordering elements within an array.

The sort() function .

It sorts the elements from the smallest to the largest if an element inside is a number and in alphabetical order in the case of a string.

Even if not popular at all, we must, however, note that there is a second parameter in this function,

that define how a given array must be ordered.

The flags present are:

— items appear normally, standard evaluation;
— the items using a numeric method appear;
— items appear as they were strings;
— It uses the local feature of PHP to set where to language we want to order the array, it can be changed using setlocale() and compare items as strings according to it;
Here is more info about the locale class
— compare items as strings using “natural ordering” have a look at the natsort() function;
— can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively;

This function takes the array indicated as a parameter as a reference and not by value, this involves two important factors.

The first is that (so be careful to modify arrays that you don’t want to change),

This allows number two, to have a different variable returned by the function.

In this case, the variable is of the boolean type and indicates whether the function was successfully executed or not.

$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy']; 
sort($dwarfs);
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[0] = Bashful
dwarfs[1] = Doc
dwarfs[2] = Dopey
dwarfs[3] = Grumpy
dwarfs[4] = Happy
dwarfs[5] = Sleepy
dwarfs[6] = Sneezy
$dwarfs = ['Doc1', 'doc2', 'Doc3', 'doc20'];
sort($dwarfs, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[0] = Doc1
dwarfs[1] = doc2
dwarfs[2] = Doc3
dwarfs[3] = doc20

the code in the second example can be written more easily by simply using the natcasesort() function

asort()

The asort() function is syntactically equal to the sister function you just saw.

The substantial difference between the two is that asort() (pay attention to the ‘a’ at the beginning of the name) is used with associative arrays.

The reason is that the main feature of asort() is to .

When it sorts the elements, the keys remain attached to the corresponding value even if the value changes position.

, which are not mandatory, and returns a true or false Boolean value based on the result of the function.

$dwarfs = array( 
'first' => 'Grumpy',
'second' => 'Happy',
'third' => 'Sleepy',
'fourth' => 'Dopey',
'fifth' => 'Bashful',
'sixth' => 'Sneezy',
'seventh' => 'Doc'
);
asort($dwarfs);
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[fifth] = Bashful
dwarfs[seventh] = Doc
dwarfs[fourth] = Dopey
dwarfs[first] = Grumpy
dwarfs[second] = Happy
dwarfs[third] = Sleepy
dwarfs[sixth] = Sneezy

rsort()

Here is another close relative of the family of functions that sorts arrays elements.

Also, this, like the other array functions you saw previously was released for the first time in the fourth version of PHP and, having the same syntax, it differs only in the substance.

There is little to say about this feature, take everything that has been said about sort() and reverse the result.

rsort() takes the array as the first parameter,

The only difference between the two functions is that here, the order of the elements goes from the highest to the lowest.

$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy']; sort($dwarfs); 
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[0] = Sneezy
dwarfs[1] = Sleepy
dwarfs[2] = Happy
dwarfs[3] = Grumpy
dwarfs[4] = Dopey
dwarfs[5] = Doc
dwarfs[6] = Bashful

arsort()

This function is based on asort().

Like all the previous functions you’ve just seen,

Also as asort() is used for associative arrays and preserves the keys of the connected values.

As you will have understood from the letter ‘r’ which stands for reverse, this function orders the result of the elements starting from the largest or highest and gradually goes down following the alphabet

$dwarfs = array( 
'first' => 'Grumpy',
'second' => 'Happy',
'third' => 'Sleepy',
'fourth' => 'Dopey',
'fifth' => 'Bashful',
'sixth' => 'Sneezy',
'seventh' => 'Doc'
);
asort($dwarfs);
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[seventh] = Doc
dwarfs[fourth] = Dopey
dwarfs[first] = Grumpy
dwarfs[second] = Happy
dwarfs[third] = Sleepy
dwarfs[sixth] = Sneezy
dwarfs[fifth] = Bashful

ksort()

Yes, by now you understand it, the array of array functions that sorts the elements is very broad, and all of them have the same syntax,

The fact that the syntax is the same is a positive thing,

The fact that they all have similar names is a little less positive.

All the functions seen so far end with the word ‘sort’, and this is easy.

So far you’ve seen ‘r’ you’ve seen ‘a’ and now you’re about to see another prefix.

Syntactically you are about to see the same one more time, two parameters, of which the mandatory array (the first), and the second consisting of flags.

Here is a simple example of the ksort() function.

$dwarfs = array( 
'first' => 'Grumpy',
'second' => 'Happy',
'third' => 'Sleepy',
'fourth' => 'Dopey',
'fifth' => 'Bashful',
'sixth' => 'Sneezy',
'seventh' => 'Doc'
);
ksort($dwarfs);
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[fifth] = Bashful
dwarfs[first] = Grumpy
dwarfs[fourth] = Dopey
dwarfs[second] = Happy
dwarfs[seventh] = Doc
dwarfs[sixth] = Sneezy
dwarfs[third] = Sleepy

krsort()

Not too much time to spend here, same procedure as ksort() but .

The keys are ordered from the last element of the alphabet to the first.

$dwarfs = [ 
'first' => 'Grumpy',
'second' => 'Happy',
'third' => 'Sleepy',
'fourth' => 'Dopey',
'fifth' => 'Bashful',
'sixth' => 'Sneezy',
'seventh' => 'Doc'
];
ksort($dwarfs);
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[third] = Sleepy
dwarfs[sixth] = Sneezy
dwarfs[seventh] = Doc
dwarfs[second] = Happy
dwarfs[fourth] = Dopey
dwarfs[first] = Grumpy
dwarfs[fifth] = Bashful

usort()

Here we have something very interesting,

The usort() function resembles the other functions with the suffix sort but it works slightly differently.

and indicates that this function uses a callback function created by the user in order to sort the elements within an array.

There are substantial differences between this and the other features we’ve seen so far,

This function takes two parameters,

The value returned by this function will decide in which position to order the element and for this reason, it will always be cast as an integer.

The callback function is one of the places where the spaceship operator developed in PHP 7 finds in its ideal environment.

If you have never used it and do not know how to use it, take a look at its features in the guide to operators in PHP

$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy']; usort($dwarfs, function (int $a, int $b) { 
return ($a <=> $b);
});
Array (
[0] => Bashful
[1] => Doc
[2] => Dopey
[3] => Grumpy
[4] => Happy
[5] => Sleepy
[6] => Sneezy
)

let’s do something more complicated using a multidimensional array with strings

function compare($a, $b) { 
return strcmp($a["dwarf"], $b["dwarf"]);
}
$dwarfs[0]["dwarf"] = 'Doc';
$dwarfs[1]["dwarf"] = 'Grumpy';
$dwarfs[2]["dwarf"] = 'Happy';
$dwarfs[3]["dwarf"] = 'Sleepy';
$dwarfs[4]["dwarf"] = 'Dopey';
$dwarfs[5]["dwarf"] = 'Bashful';
$dwarfs[6]["dwarf"] = 'Sneezy';
usort($dwarfs, "compare"); while (list($key, $value) = each($dwarfs)) {
echo "\$dwarfs[$key]: " . $value["dwarf"] . "\n";
}
$dwarfs[0]: 'Bashful'
$dwarfs[1]: 'Doc'
$dwarfs[2]: 'Dopey'
$dwarfs[3]: 'Grumpy'
$dwarfs[4]: 'Happy'
$dwarfs[5]: 'Sleepy'
$dwarfs[6]: 'Sneezy'

As you may have noticed, the usort() function removes existing keys.

It assigns new keys to the elements of the array during the sorting phase.

uasort()

Here the situation becomes much more interesting than in the functions seen above,

uasort() contains two letters, ‘u’ indicating that the function requires a callback from the user, and ‘a’ indicating that this function works preferably on associative arrays.

Consider the operation of this function as a cross between usort() and asort().

This function orders an array in such a way that the indexes of the array hold their correlation with the values of the array to which they are associated

function compare($a, $b){
return ($a <=> $b);
}
$dwarfs = [
'first' => 'Grumpy',
'second' => 'Happy',
'third' => 'Sleepy',
'fourth' => 'Dopey',
'fifth' => 'Bashful',
'sixth' => 'Sneezy',
'seventh' => 'Doc' ];
uasort($dwarfs, 'compare'); print_r($dwarfs); Array (
[fifth] => 'Bashful',
[seventh] => 'Doc',
[fourth] => 'Dopey',
[first] => 'Grumpy',
[second] => 'Happy',
[third] => 'Sleepy',
[sixth] => 'Sneezy',
)

ukort()

Very similar to the uasort() function,

This differs from the fact that it sorts array .

function compare($a, $b){ 
return ($a <=> $b);
}
$dwarfs = [
'first' => 'Grumpy',
'second' => 'Happy',
'third' => 'Sleepy',
'fourth' => 'Dopey',
'fifth' => 'Bashful',
'sixth' => 'Sneezy',
'seventh' => 'Doc' ];
uksort($dwarfs, 'compare');
foreach ($dwarfs as $index => $name) {
echo "dwarfs[" . $index . "] = " . $name . "\n";
}
dwarfs[fifth] = Bashful
dwarfs[first] = Grumpy
dwarfs[fourth] = Dopey
dwarfs[second] = Happy
dwarfs[seventh] = Doc
dwarfs[sixth] = Sneezy
dwarfs[third] = Sleepy

This is the first function of this article which has a different syntax than the others.

natsort() where ‘nat’ stands for Natural Order.

Before advancing and explaining what the purpose of this function is, it is necessary to explain what the natural order is.

Without going into too much detail,

If I asked you to sort the numbers 1, 5, 10, 15 as a human you would list them exactly as written above,

The final result looks more like this 1, 10, 15, 5.

Now that you understand more about the type of order we go into the details of this array function.

natsort() takes only one parameter, which is the array we actually want to modify.

It is taken into consideration as a reference, which means that the array entering the function will not be the same as the one coming out, so be careful.

This function is very simple to implement, here is an example:

$arrayA = $arrayB = [1, 5, 10, 15]; asort($arrayA); 
Array ( [0] => 1 [2] => 10 [3] => 15 [1] => 5 )
natsort($arrayB);
Array ( [0] => 1 [1] => 5 [2] => 10 [3] => 15 )

natcasesort()

We have already seen this function a couple of examples ago,

this function sorts the elements of an array in the same way that a human would,

natcasesort() works with both numbers and letters and one of the main features is that it maintains the key-value pair between the elements.

this means that the order of the elements within the variable changes after the function has been executed and it is not possible to go back.

the type of variable that the function returns is boolean, and changes based on the success or failure of the operation.

the difference between this and natsort() is that this function is case-insensitive.

$dwarfs = ['Doc1', 'doc2', 'Doc3', 'doc20']; 
print_r(natcasesort($dwarfs));
Array ( [0] => Doc1 [1] => doc2 [2] => Doc3 [3] => doc20 )

array_multisort()

This is a rather complicated function.

It is used to sort more than one array at the same time or to sort different elements within a multidimensional array.

array_multisort() works with both numeric and associative arrays, in the case of elements with string-type keys they are retained, numerical elements are instead reset and start at 0.

As mentioned above there are several parameters,

they are divided into arrays that must be ordered and flags that indicate the type of order to be implemented.

is mandatory and is the primary array that must be ordered.

indicates the type of order to be used for the array indicated above, this parameter is not mandatory, and indeed, it can be replaced by the third parameter or be completely eliminated.

The values ​​of this flag are SORT_ASC and SORT_DESC and are fairly self-explanatory.

indicates the type of order to be executed, the keys are the same as the section related to the sort() function just above.

The parameters ranging from the fourth onwards are simply other arrays, which are sorted together with the first.

$dwarfs = ['Doc', 'Grumpy', 'Happy', 'Sleepy', 'Dopey', 'Bashful', 'Sneezy'];
$originals = ["Mickey Mouse","Pete", "Goofy", "Minnie Mouse", "Pluto"];
array_multisort($dwarfs, $originals); print_r($dwarfs); print_r($originals);
Array (
[0] => Bashful
[1] => Doc
[2] => Dopey
[3] => Grumpy
[4] => Happy
[5] => Sleepy
[6] => Sneezy
)
Array (
[0] => Goofy
[1] => Mickey Mouse
[2] => Minnie Mouse
[3] => Pete
[4] => Pluto
)

Conclusion

Here are another few arrays’ functions to add to your collection.

while others will require more practice to be used to their full potential.

Some details to keep in mind are that almost all the functions that order the elements within arrays end up with the word ‘sort’,

they have one or two letters as a prefix that indicate the type of operation and most of these functions take arrays of parameters as a reference instead of a value.

If these functions seemed too difficult, take a look at the basics on how to build arrays.

You can simply add this page to your browser’s favourites or if you want to learn more, register for the newsletter and be informed every time a new post is published.

If you are ready to learn more about this topic instead you check the most popular PHP functions out that work with arrays elements.

***

Learning to program is a long process and requires a lot of energy.

There is a lot of information online and almost all of it is scattered and without a logical sense.

For this reason, I concentrate on creating posts in a series like this article you just read.

It helps but does not have the same value and structure as a book.

If you don’t like reading or don’t want to spend your time between notes and post-it, now there’s an easier way that has helped me a lot over the years.

Video lessons and video tracks.

One of the best platforms in the world is served by the Treehouse and, with its certified teachers, it has already helped thousands of web developers around the world.

Today for you there are also 4 Months Off on their Basic Annual Plan

CLICK HERE AND TAKE ADVANTAGE OF THE OFFER NOW

***


Originally published at http://anastasionico.uk.

Nico Anastasio

Written by

An Italian coder and design enthusiast. I publish content on my blog that helps web developers improve their skills and share knowledge. http://anastasionico.uk