Array function in PHP [Part 2]
Tags: php, arrays, sortingarray, webdev
Published: 2019-04-29 13:53:23

---
title: Array function in PHP [Part 2]
published: true
description: Everybody can work with arrays.Fewer people can work with element inside the arrays.Mastering these elements using PHP built-in function is just for a few.
tags: PHP, arrays, sorting array, web development, 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/0ifl2bmhqn9fllyix1cr.jpg
series: arrays exposed
---

### 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](http://anastasionico.uk/blog/php-array-functions-exposed),

in the second chapter, [we focused on the most used functions](http://anastasionico.uk/blog/array-function-in-php), 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](http://anastasionico.uk/blog/filtering-with-array-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 **sorting the elements within an array**.

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](https://www.reddit.com/r/PHP/comments/7yumuy/why_is_php_written_in_c_instead_of_c/?depth=2)

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 **takes as an argument, you guessed it, an array**.

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,

**This parameter is not mandatory and consists of one or more flags** that define how a given array must be ordered.

The flags present are:

**SORT\_REGULAR ** — items appear normally, standard evaluation;  
**SORT\_NUMERIC ** — the items using a numeric method appear;  
**SORT\_STRING ** — items appear as they were strings;  
**SORT\_LOCALE\_STRING ** — 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](https://www.php.net/manual/en/class.locale.php)  
**SORT\_NATURAL ** — compare items as strings using “natural ordering” [have a look at the _natsort()_ function](http://anastasionico.uk/blog/sorting-arrays-element-using-php-functions#natsort);  
**SORT\_FLAG\_CASE ** — 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 **the array itself changes not its duplicate and no copy will be created** (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](https://www.youtube.com/watch?v=5qXvj56dmmw).

The reason is that the main feature of _asort()_ is to **preserve array indexes**.

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

**It also uses flags as the second parameter** , 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, **a non-mandatory flag that determines the arrangement as a second parameter and returns a boolean value as a result of the function.**

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, **it sorts the elements of an array and uses the same syntax.**

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

**The key letter ‘a’ at the beginning of the name of the function means, in fact, associative.**

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.

**The confusing part is the prefix,**

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

**‘k’: the letter ‘k’ stands for key and indicates that this time the property we are going to order is not the value of the elements of an array but their keys are also called indexes.**

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 **as described by the letter ‘r’ the result is reversed**.

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.

**The ‘u’ used as a prefix, in this case, stands for ‘user’** and indicates that [this function uses a callback function created by the user](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) 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 first is the array we want to work on, the second parameter, in this case also mandatory, is the callback function.**

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](http://anastasionico.uk/blog/php-operators#spaceship)

```
$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,

**It is also part of the ‘sort’ family of functions and also like some of the functions you just read and consists of more than one indicative letter.**

_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 **keys rather than values**.

```
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](https://en.wikipedia.org/wiki/Natural_sort_order).

Without going into too much detail, **the human brain is used to thinking differently than how a processor analyzes numbers and letters,**

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

**a computer instead takes the first number in this case the options are 1 and 5, sort them, then move to the second, the third and so on.**

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.

**The value returned by the function is a boolean value and indicates the success or failure of the operation.**

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.

**_natcasesort()_ takes a single parameter, it is a mandatory element and is taken as a reference,**

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 takes several parameters, including multiple arrays, multidimensional arrays, flags, and so on and so forth.**

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.

**The first parameter** is mandatory and is the primary array that must be ordered.

**The second parameter** 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.

**The third parameter** 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.

**I’m sure you’ll find some of them very easy to adopt right away,** 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.

**As for the other functions in this series, there is no need to learn them by heart,** [If these functions seemed too difficult, take a look at the basics on how to build arrays.](http://anastasionico.uk/blog/php-array-functions-exposed)

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](http://anastasionico.uk/blog/array-function-in-php) 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](http://treehouse.7eer.net/c/1374240/294479/3944)


***

[ ![subscribe-Medium.jpg](https://cdn.filestackcontent.com/RrGR27noRgSByWvS0Sck)](http://eepurl.com/dIZqjf)

* * *

_Originally published at_ [_http://anastasionico.uk_](http://anastasionico.uk/blog/sorting-arrays-element-using-php-functions)_._