Php sort array by value. Sorting a php array in various ways

Last update: 1.11.2015

is_array function

The is_array() function checks if the variable is an array, and if it is, it returns true , otherwise it returns false . For example:

$isar = is_array($technics); echo ($isar==true)?"this is an array":"this is not an array";

count/sizeof functions

The count() and sizeof() functions get the number of array elements:

$number = count($technics); // same as // $number = sizeof($technics); echo "The technics array has $number elements";

shuffle functions

The shuffle function shuffles array elements randomly:

$os = array("Windows 95", "Windows XP", "Windows Vista", "Windows 7", "Windows 8", "Windows 10"); shuffle($os); print_r($os); // one of the options // Array ( => Windows 95 => Windows 7 => Windows Vista => Windows XP => Windows 10 => Windows 8)

compact functions

The compact function allows you to create an associative array from a set of variables, where the variable names themselves will be the keys:

Apple II => Apple => 1978) ?>

The compact function receives a set of variables in parentheses. Each variable is quoted without the $ sign. The result of the function is a new array.

Sorting arrays

There are two types of sorting in PHP: sorting strings alphabetically and sorting numbers in ascending/descending order. If the values ​​to be sorted are strings, then they are sorted alphabetically; if they are numbers, then they are sorted in ascending numerical order. PHP chooses sorting type by default.

To sort in ascending order, use the asort function:

"Lenovo IdeaTab A3500", "samsung" => "Samsung Galaxy Tab 4", "apple" => "Apple iPad Air"); asort($tablets); echo "

    "; foreach ($tablets as $key => $value) ( ​​echo "
  • $key: $value
  • "; ) echo "
"; ?>

In this case, the array values ​​represent strings, so PHP will choose to sort alphabetically. However, with the help of an additional parameter, we can explicitly tell the PHP interpreter the sort type. This parameter can take three values:

    SORT_REGULAR: automatic sort selection

    SORT_NUMERIC: numeric sort

    SORT_STRING: sort alphabetically

Let's explicitly specify the sort type:

Asort($tablets, SORT_STRING);

To sort an array in reverse order, use the arsort function:

Arsort($tablets);

Key sorting

The asort function sorts by element values, but there is also a sort by keys. It is represented by the ksort function:

Ksort($tablets, SORT_STRING);

Sorting by keys in reverse order is done by the krsort() function:

Krssort($tablets);

natural sort

Although the above sorting functions do their job well, they are still not enough. For example, let's sort the following array in ascending order:

Windows 10 => Windows 7 => Windows 8) ?>

Since the values ​​represent strings, PHP sorts alphabetically. However, this sort is not sensitive to numbers and case. Therefore, the value "Windows 10" will go at the very beginning, and not at the end, as it should have been. And to solve this problem, PHP has the natsort() function, which performs a natural sort:

Windows 7 => Windows 8 => Windows 10) ?>

If we also want the sort to be case-insensitive, we can use the natcasesort() function.

I'd like to add my own solution here as it offers features that the other answers don't.

Specifically, the benefits of this solution include:

  • He reusable: You are specifying the sort column as a variable, not hardcoding.
  • flexible: You can specify multiple sort columns (as many as you like) - extra columns are used as delimiters between items that initially compare the same.
  • reversible: you can specify that sorting should be canceled - individually for each column.
  • expandable: if the dataset contains columns that cannot be mapped in a "dumb" way (such as date strings), you can also specify how to convert those elements to a value that can be directly matched (such as a DateTime instance).
  • associative if you want: This code sorts the elements, but you choose the actual sort function (usort or uasort).
  • Finally, it doesn't use array_multisort: while array_multisort is handy, it does depend on creating a projection of all your input before sorting. This consumes time and memory and can be just prohibitive if your dataset is large.

Code

function make_comparer() ( // Normalize criteria up front so that the comparer finds everything tidy $criteria = func_get_args(); foreach ($criteria as $index => $criterion) ( $criteria[$index] = is_array($criterion) array_pad($criterion, 3, null) : array($criterion, SORT_ASC, null); ) return function($first, $second) use (&$criteria) ( foreach ($criteria as $criterion) ( // How will we compare this round? list($column, $sortOrder, $projection) = $criterion; $sortOrder = $sortOrder === SORT_DESC ? -1: 1; // If a projection was defined project the values ​​now if ($ projection) ( $lhs = call_user_func($projection, $first[$column]); $rhs = call_user_func($projection, $second[$column]); ) else ( $lhs = $first[$column]; $rhs = $second[$column]; ) // Do the actual comparison; do not return if equal if ($lhs< $rhs) { return -1 * $sortOrder; } else if ($lhs >$rhs) ( return 1 * $sortOrder; ) ) return 0; // tiebreakers exhausted, so $first == $second ); )

How to use

$data = array(array("zz", "name" => "Jack", "number" => 22, "birthday" => "12/03/1980"), array("xx", "name" => "Adam", "number" => 16, "birthday" => "01/12/1979"), array("aa", "name" => "Paul", "number" => 16, " birthday" => "03/11/1987"), array("cc", "name" => "Helen", "number" => 44, "birthday" => "24/06/1967")),) ;

Basics

The make_comparer function takes a variable number of arguments that define the desired type and returns a function that you should use as an argument to usort or uasort .

The simplest use case is to pass the key you want to use to compare data items. For example, to sort $data by the name element you do

usort($data, make_comparer("name"));

The key can also be a number if the elements are numeric indexed arrays. For the example in the question it would be

Usort($data, make_comparer(0)); // 0 = first numerically indexed column

Multiple sort columns

You can specify multiple sort columns by passing additional options to make_comparer . For example, to sort by "number" and then by a null-indexed column:

Usort($data, make_comparer("number", 0));

Advanced features

Additional functionality is available if you specify the sort column as an array instead of a simple string. This array must be numerically indexed and must contain the following elements:

0 => the column name to sort on (mandatory) 1 => either SORT_ASC or SORT_DESC (optional) 2 => a projection function (optional)

Let's see how we can use these functions.

reverse sort

Sort by name in descending order:

Usort($data, make_comparer(["name", SORT_DESC]));

To sort by number descending and then by name:

Usort($data, make_comparer(["number", SORT_DESC], ["name", SORT_DESC]));

Custom Predictions

In some scenarios, you may need to sort on a column whose values ​​do not allow for a good sorting. The "Birthday" column in the sample dataset matches this description: it makes no sense to compare birthdays as strings (because "01/01/1980" comes before "10/10/1970"). In this case, we want to specify how to project the actual data into a form that can be directly compared to the desired semantics.

Projections can be specified as any type of callable : strings, arrays, or anonymous functions. A projection is supposed to take one argument and return its projected form.

It should be noted that while predictions are similar to the custom comparison functions used with usort and family, they are simpler (you only need to convert one value to another) and use all the functions already baked into make_comparer .

Let's sort the example dataset without projection and see what happens:

Usort($data, make_comparer("birthday"));

This was not the desired result. But we can use date_create as a projection:

Usort($data, make_comparer(["birthday", SORT_ASC, "date_create"]));

This is the correct order we wanted.

There are many other things that forecasts can achieve. For example, a quick way to get case insensitive is to use strtolower as a projection.

However, I should also mention that it's better not to use predictions if your dataset is large: in that case, it would be much faster to project all your data manually and then sort without using projection, although doing so will increase memory usage for faster sorting speed.

Finally, here's an example that uses all the features: it sorts first by number descending, then ascending by day:

Usort($data, make_comparer(["number", SORT_DESC], ["birthday", SORT_ASC, "date_create"]));

Good day, dear readers of our blog! On our site, we have already touched on the topic of arrays and this was an example of how to make . There was also an article about how arrays were also used to solve this problem. And today we will talk about how to sort multidimensional array. So let's get started.
Let's take an array "goods" of the following form:

200, "manufacture" => "TOO Tselina"); $goods = array("price" => 400, "manufacture" => "IP Devyatkin"); $goods = array("price" => 800, "manufacture" => "JSC Agrarnik"); $goods = array("price" => 790, "manufacture" => "ZAO Krasny Vostok"); ?>

You need to sort this array by key. To do this, we use the "ksort" function:

xsort($goods); print_r($goods); ?>

As a result, we get a sorted array by key:

Array ( => Array ( => 400 => IP Devyatkin) => Array ( => 200 => Tselina LLP) => Array ( => 800 => JSC Agrarnik) => Array ( => 790 => CJSC Krasny Vostok ))

As you can see, the keys are in ascending order from 45 to 89. Now we need to sort the array by the value of the “price” key. To do this, we will use the “uasort” function and write a custom function “sort_p” for it:

sort_p($a, $b) ( return strcmp($a["price"], $b["price"]); ) uasort($goods, "sort_p"); print_r($goods); ?>

As a result, we get a sorted array by the key "price":

Array ( => Array ( => 200 => Tselina LLP) => Array ( => 400 => IP Devyatkin) => Array ( => 790 => ZAO Krasny Vostok) => Array ( => 800 => JSC Agrarnik))

As you can see, the values ​​of the “price” key are in ascending order from 200 to 800. To change the values ​​of the “price” key in the reverse order, in descending order, we swap the parameters of the “strcmp” function in the user-defined function “sort_p”:

b["price"],$ a["price"]); ) uasort($goods, "sort_p"); print_r($goods); ?>

We get the following result:

Array ( => Array ( => 800 => JSC Agrarnik) => Array ( => 790 => ZAO Krasny Vostok) => Array ( => 400 => IP Devyatkin) => Array ( => 200 => Tselina LLP))

As you can see, now the values ​​of the “price” key are in descending order from 800 to 200. Now we need to sort the array by the value of the two keys “manufacture” and “price”, for this we will write a custom function “sort_pm”:

sort_pm($a, $b) ( $r1 = strcmp($a["manufacture"], $b["manufacture"]$a["price"], $b["price"]) : $r1; ) uasort ($goods, "sort_pm"); print_r($goods); ?>

Now the sorting occurs by the values ​​of the two keys in ascending order, the priority is the key "manufacture".

Array ( => Array ( => 800 => JSC Agrarnik) => Array ( => 790 => CJSC Krasny Vostok) => Array ( => 400 => IP Devyatkin) => Array ( => 200 => Tselina LLP))

If you prefer the values ​​of the "price" key, then swap the parameters of the "strcmp" functions and write the "sort_pm" function as follows:

$a["price"], $b["price"]); return ($r1 == 0) ? strcmp() : $r1; ) uasort($goods, "sort_pm"); print_r($goods); ?>

That is, the parameters of the "strcmp" functions have been changed. Now the values ​​of the "price" key will be prioritized, which means that the sorting will be carried out first of all by them, then the values ​​of the "manufacture" key will be sorted. Let's explain with the following example:

200, "manufacture" => "TOO Tselina"); $goods = array("price" => 400, "manufacture" => "IP Devyatkin"); $goods = array("price" => 400, "manufacture" => "AO Holiday");$goods = array("price" => 800, "manufacture" => "JSC Agrarnik"); $goods = array("price" => 790, "manufacture" => "ZAO Krasny Vostok"); function sort_pm($a, $b) ( $r1 = strcmp( $a["price"], $b["price"]); return ($r1 == 0) ? strcmp( $a["manufacture"], $b["manufacture"]) : $r1; ) uasort($goods, "sort_pm"); print_r($goods); ?>

(PHP 4, PHP 5, PHP 7)

array_multisort - Sorts multiple arrays or multidimensional arrays

Description

Function array_multisort() can be used to sort several arrays at once or one multidimensional array according to one or more dimensions.

Array1_sort_order

Order to sort the above argument array. Or SORT_ASC to sort in ascending order, or SORT_DESC to sort in descending order.

This argument may be swapped with array1_sort_flags or omitted altogether. In this case, the meaning is SORT_ASC.

Array1_sort_flags

Collation settings for the above argument array:

Sort flag:

  • SORT_REGULAR- normal comparison of elements (without changing types)
  • SORT_NUMERIC- comparing elements as numbers
  • SORT_STRING- comparing elements as strings
  • SORT_LOCALE_STRING- comparing elements as strings, given the current locale. The locale is used, which can be changed using the function setlocal()
  • SORT_NATURAL- comparing elements as strings using the "natural order" algorithm, just like in a function natsort()
  • SORT_FLAG_CASE- can be combined (binary OR) with SORT_STRING or SORT_NATURAL for case-insensitive sorting

This argument may be swapped with array1_sort_order or omitted altogether. In this case, the meaning is SORT_REGULAR .

...

Additional arrays, optionally following the sort order and flags.

Return Values

returns TRUE upon successful completion or FALSE in case of an error.

List of changes

Examples

Example #1 Sorting multiple arrays

$ar1 = array(10 , 100 , 100 , 0 );
$ar2 = array(1 , 3 , 2 , 4 );
array_multisort ($ar1 , $ar2 );

Var_dump($ar1 );
var_dump($ar2 );
?>

In the example above, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The elements of the second array corresponding to the identical elements of the first (100 and 100) will also be sorted.

array(4) ( => int(0) => int(10) => int(100) => int(100) ) array(4) ( => int(4) => int(1) => int (2) => int(3) )

Example #2 Sorting a multidimensional array

$ar = array(
array("10" , 11 , 100 , 100 , "a" ),
array(1 , 2 , "2" , 3 , 1 )
);
array_multisort ($ar [ 0 ], SORT_ASC , SORT_STRING ,
$ar [ 1 ], SORT_NUMERIC , SORT_DESC );
var_dump($ar);
?>

In the example above, after sorting, the first array will contain "10", 100, 100, 11, "a" (its elements have been sorted in ascending order), and the second array will contain 1, 3, "2", 2, 1 (elements are sorted as numbers, in descending order).

array(2) ( => array(5) ( => string(2) "10" => int(100) => int(100) => int(11) => string(1) "a" ) = > array(5) ( => int(1) => int(3) => string(1) "2" => int(2) => int(1) ) )

Beispiel #3 Sorting results from a database

In this example, each element of the data array represents a table row. This type of data is typical for database records.

Sample data:

# volume | volume edition | edition -------+-------- 67 | 2 86 | 1 85 | 6 98 | 2 86 | 6 67 | 7

The data is represented as an array named data . Usually they can be obtained, for example, using a loop from the function mysql_fetch_assoc().

$data = array("volume" => 67 , "edition" => 2 );
$data = array("volume" => 86 , "edition" => 1 );
$data = array("volume" => 85 , "edition" => 6 );
$data = array("volume" => 98 , "edition" => 2 );
$data = array("volume" => 86 , "edition" => 6 );
$data = array("volume" => 67 , "edition" => 7 );
?>

In our example, we will sort by volume in descending order, and by edition in ascending order.

We have an array of strings, but array_multisort() we need an array of columns, so we first use the following code to get the columns and then we sort.

// Get a list of columns
foreach ($data as $key => $row ) (
$volume [ $key ] = $row [ "volume" ];
$edition [ $key ] = $row [ "edition" ];
}

// Sort the data by volume in descending order and by edition in ascending order
// Add $data as last parameter to sort by common key
array_multisort($volume , SORT_DESC , $edition , SORT_ASC , $data );
?>

And talk with you about the various "goodies" that you may need when finalizing ready-made solutions.

And one of them, with whom I personally have to meet quite often at work, is array sortingphp.

Such frequent meetings were due to the fact that, as practice shows, people like from time to time, for a change, to change the sequence of displaying objects on their site - be it goods in the online store, user messages on the forum or blocks of information on business card sites.

For beginners, I will only remind you of the main provisions in the most understandable language. Therefore, if you do not classify yourself as such, you can immediately move on to examples of tasks and ways to solve them.

A little theory about php arrays

PHP is a server-side programming language. Server based, because scripts that are run by users through the web interface (Internet browser) are stored and executed on the server.

PHP scripts are hidden from the view of the average user. In the window of your browsers, you see only the results of their execution.

An array in programming is a collection of some data. They consist of array elements, which are pairs [index] => [value].

Arrays can be static, dynamic, heterogeneous, etc. (a whole science) 🙂 To work with them, classification into one-dimensional and multidimensional is quite enough for us.

In order for you to understand the difference between them, it is enough to give a description of their structure.

One dimensional php array:

Array ( => 1 => 2 => 3)

php multidimensional array:

Array ( => Array ( => 1) => Array ( => 2) => Array ( => 3))

Noticed? If not, pay attention to the elements of the php multidimensional array. They themselves are arrays. Those. A multidimensional array is a collection of arrays. The level of their nesting can be arbitrarily large.

Now I think it's clear 🙂

I would also like to separately highlight the concept of an associative array php. In real life, they are not as common as usual, but still have a place to be.

In short, these are arrays in which the key and value of the array element are inextricably linked and between them there is a certain logical connection that should never be broken.

An example of an associative array is the following construction:

Array ( => 12 [name] => Ivanov Ivan Ivanovich [average_score] => 3)

As you can see, here the values ​​of the keys and values ​​of the array elements are closely related and in no case should this connection be broken. Because of this, associative arrays are very often called "dictionaries" or "dictionaries".

Therefore, this feature must be taken into account when sorting the php array, because not all methods are suitable for such structures.

In PHP itself, arrays are created in two ways:

  1. $books = array('ABC', 'Primer', 'Dictionary); or $books = array('azb' => 'ABC', 'buk' => 'Primer', 'slov' => 'Dictionary'); The second option is used when the element needs to explicitly specify the key field (relevant for associative arrays). If not specified, the array element keys will default to numbers. Starting from 0 (zero).
  2. $books = 'ABC'; $books = 'Primer'; $books = 'Primer';

In both cases $books will be an array. So, if you meet such constructions in the code of your site, it will no longer be something incomprehensible to you 🙂

If you want to learn more about php arrays, then I recommend that you watch the following video:

Let me remind you that in order to see the structure of the array on your screen, after declaring the array in the site code, you must write the following construction:

echo"

"; print_r(array_var); die();

If the variable you print out is an array, then the text will begin with the following line:

array(...

And a few more words about the topic of our article - array sortingphp.

As you can understand, the data in the arrays is structured and the elements are arranged in a certain sequence. In order to change it, we just need to sort the php array, which is implemented by ready-made language functions.

Therefore, all we need to do is call the required function after declaring the array, specifying it as a parameter.

Let's move on to an overview of the functions themselves.

php array sort functions

Their full list is presented in the official documentation of the php language:

In order to sort the php array using a specific function, you will need to call it after declaring the array and filling it with values, specifying our array as parameters to it. For example:

$cars = array("Toyota", "Mazda", "Mitsubishi"); sort($cars);

Let's briefly consider the functionality of each of them. Functions will be specified in the format in which they will need to be called in the code, i.e. "name(parameter1, parameter2, ...);".

Do not forget to put ";" after the function call, because without it, a beautiful error message will appear on the screen 🙂

As an illustrative example, let's take a simple one-dimensional array in which both keys and values ​​will be unordered so that the results of executing functions are more visual and understandable.

Array ( => 11 => 18 => 9)

So, how can you sort an array in the right order in php?

Functions simple php array sort by value

If you prefer watching video material to reading, then I would like to recommend you to watch this video, which clearly and clearly demonstrates the work of the php array sorting functions from this block:

If after it you still have questions, then you can find more detailed information on each function below.

sort($array, $flag); is one of the simplest and most requested functions. Allows you to sort the array in ascending order in php, taking into account the values ​​of the elements, i.e. they will be arranged from the smallest value to the largest one. It takes as parameters an array variable and one of the sorting flags, which allows you to change the sorting behavior.

List of flags:

  • SORT_REGULAR - elements are compared without changing types
  • SORT_NUMERIC - elements are compared as numbers
  • SORT_STRING - elements are compared as strings
  • SORT_LOCALE_STRING - string comparison, but taking into account the current locale.
  • SORT_NATURAL - string comparison of elements, considering their natural order (like natsort)
  • SORT_FLAG_CASE - case insensitive sorting of php array elements (can be combined with SORT_STRING or SORT_NATURAL bitwise OR).

But, in most cases, the result of the function execution is correct even without these specifying flags. By default (if nothing is specified) SORT_REGULAR will be used.

Our test array after calling the sort() function will look like this:

Array ( => 9 => 11 => 18)

As you can see, after sorting the array by values, the values ​​of their keys also changed, because sort works without maintaining the key-value relationship, as stated in the official php documentation.

As a result, this option is suitable for the vast majority of cases.

sort($array, $flag); is a function that is the antagonist of sort. The antagonist, because it sorts the array in the same way, only not in ascending order, but in descending order, i.e. the php array elements with the largest values ​​will go first.

You can also pass two parameters to it: the array itself and the sort flag, and it, like sort, is more suitable for one-dimensional arrays. Our test array after calling this function will take the following form:

Array ( => 18 => 11 => 9)

sort($array, $flag); is a php function for sorting an array by value, the mechanism of which is also very similar to sort.

With the only exception that it allows you to sort the php array by the value of its elements while maintaining the key-value relationship.

Thus, this feature is great for php associative array sorting, i.e. structures where this connection is logical and important.

Elements will be arranged in ascending order, because it allows you to sort an associative php array by value, preserving the keys.

You can also pass two parameters. Our test array will look like this:

Array ( => 9 => 11 => 18)

As you can see, the difference from sort is only in saving the keys of the values ​​by which the php array is sorted. This is called maintaining the key-value relationship, which is incredibly important when sorting php associative arrays.

arsort($array, $flag); is another php function to sort an array by value. Antagonist asort.

It works on the same principle as the mentioned function, only sorting the php array in this case will be in descending order. Also a great option when sorting php associative arrays.

After calling this function, our example will look like this:

Array ( => 18 => 11 => 9)

Advanced php array sort functions by value

This block of functions, unlike the previous ones, which allowed you to change the order in descending/ascending order, will allow you to add variety and arrange elements in different sequences other than the “traditional” ones.

This feature makes them suitable for solving various non-standard tasks, sometimes very interesting 🙂

natsort($array);- this function brings variety to the family of sort-like solutions, since the mechanism of its work is fundamentally different from them. natsort has only one single input parameter - it is an array to be sorted, the values ​​​​of which will be arranged in the order familiar to a person. Such an algorithm is called "natural ordering", which in Russian means "natural order". In order to understand the meaning of this statement, we will take another array as an example:

Array ( => student5 => student1 => student10)

In addition, the natsort function preserves the key-value relationship. Therefore, we will compare its work with asort, which is as similar as possible to it. After calling the last one, our array will take the following form:

Array ( => student1 => student10 => student5)

If you call natsort, then the resulting array will be like this:

Array ( => student1 => student5 => student10)

I think the difference is now visible to you and the principle of natsort will be clear to you :-)

shuffle($array);- a wonderful and very useful function with which you can shuffle a php array and place its elements in random order.

It is very convenient when you need to place the goods of an online store in a category or on another page in a random order, or when you go to a business card site, show users different blocks of information each time in a different sequence.

In this case, the key-value relationship is not preserved. That is, the array used by us in the previous example, for me personally, took the form:

Array ( => student10 => student5 => student1)

Moreover, after each function call, the order of the elements will be different.

The functions considered by us earlier are quite simple and the mechanism of their work is clear. An array is passed as a parameter, the contents of which must be sorted by the values ​​of its elements, as well as a flag that can change the sorting behavior (you can safely do without it).

Among programmers, it is quite popular, because. allows you to solve any task related to sorting (using a variety of algorithms) with the help of its function.

One of these tasks is php in the required field.

To visually show you how the following functions work, for example, take the following array:

Array ( => Array ( => 32) => Array ( => 11) => Array ( => 27))

As you can see, it is multidimensional, because its elements are arrays, the structure of which is identical: they all have a field with the key "id". And now our task is to sort these elements in ascending order, i.e. so that the elements in the main array are located in accordance with the value of the fields in the subarrays.

Needless to say, it's a fairly common problem. The following functions will help us solve it:

usort($array, 'function');- PHP function for sorting a multidimensional array by the desired field.

Allows you to sort the elements of a php array without maintaining a key-value relationship in accordance with a user-defined function, the name of which is passed as the second parameter when calling usort.

The function itself is described separately. For our example, to sort the elements of a multi-dimensional php array by the ['id'] field in ascending order, the custom function would look like this:

Function myCmp($a, $b) ( if ($a["id"] == $b["id"]) return 0; return $a["id"] > $b["id"] ? 1 : -1; )

All we need now to start sorting is to make a call to usort($array, 'myCmp'); at the right place in the code. Specifies the name of the array variable as the first parameter.

As a result, we will get the following:

Array ( => Array ( => 11) => Array ( => 27) => Array ( => 32))

uasort($array, 'function');- another php function for sorting a multidimensional array by the desired field.

Works similar to usort, but retains the key-value relationship, which makes this function suitable for sorting multidimensional associative arrays.

The custom function for our example will be the same. The results of its execution will look like this:

Array ( => Array ( => 11) => Array ( => 27) => Array ( => 32))

To change the sort order of elements and make some additional data transformations, it will be necessary to edit the custom function, as you might have guessed yourself 🙂

For example, if your arrays, which are elements of the source, will contain a field [‘name’] with a string value, then a custom function for sorting a multidimensional php array by this field in ascending order will look like this:

Function myCmp($a, $b) ( if (strcasecmp($a["name"], $b["person"]["name"]) == 0) return 0; return strcasecmp($a["name "], $b["name"]) > 0 ? 1: -1; )

Sorting php arrays using custom functions is not the easiest option, but it is very flexible in customization, and if you master it, it will become your favorite solution.

array_multisort($array1, $array2, $flag);- in the end, I saved the most terrible and obscure php function for sorting an array. It takes two arrays as inputs and the same sorting flags that you can specify with sort-like functions. Array_multisort works as follows: the first parameter is the array to be sorted, the second array is the sort order of the first, after which the second array is sorted by analogy with the first. Instead of an array representing the sort order, you can use the constants SORT_DESC to sort the array in descending order and SORT_ASC in ascending order. To all this confusion, you can still add sorting flags that can come after all arrays.

$books = array(32, 11, 27); $sort_array = array(1, 2, 3); array_multisort($books, $sort_array);

In this example, I have sorted a simple one-dimensional array $books according to the array $sort_array. As a result, the first array took the following form:

Array ( => 11 => 27 => 32)

And the second one went like this:

Array ( => 2 => 3 => 1)

That is, it is sorted according to the first one. Here is such a parsley 🙂

Learn more about array_multisort in the following video. Also there you will find additional examples of its use:

This function can also be used to sort multidimensional arrays:

$books = array(array(32), array(11), array(27)); $sort_array = array(1, 2, 3); array_multisort($books, $sort_array);

The $books array will look like this:

Array ( => Array ( => 11) => Array ( => 27) => Array ( => 32))

At the same time, in this function, you can specify several arrays, sorting by several fields. In this case, the results of sorting the previous arrays will affect the subsequent ones, which will eventually lead to sorting the most recent one according to various criteria.

Here is such a kind of "snowball" in php.

When sorting a php array using this function, the key-value relationship is preserved for associative arrays, but not for numeric ones.

Programmers who have tested the operation of various functions note that when sorting a multidimensional array, php array_multisort shows better results than usort.

But array_multisort will not be able to handle all the tasks that usort can do. For example, the same sorting a multidimensional arrayphp by required field. So in each individual case, you need to analyze your chances of success when using one or another design.

Personally, I can say that I dislike array_multisort a little because of its complexity and the increased brain strain that comes with trying to represent the final array sorted with it.

Therefore, I try not to use it unnecessarily, preferring usort and simpler functions, which I encourage you to do as well 🙂

The functions we discussed earlier allow you to sort arrays in php by the value of the elements. Let's talk about how you can perform a similar action on element keys.

PHP functions to sort array by key

Before we move on to an overview of the functions of this group, I would like to say that they all have one common feature- they all maintain a key-value relationship. Otherwise, in fact, it could not be, because. then they wouldn't make sense.

Such is the feature. Let's consider each function in more detail.

ksort($array, $flag);- the function is an analogue of asort, only the ordering of elements in the array will occur not by values, but by keys.

This construct has two input parameters: a php array to be sorted and one of the sorting flags, a complete list of which you can find in the description of the sort function (it is optional). This php function allows you to sort an array in ascending order.

To demonstrate his work, let's return to the example described at the very beginning of the article:

Array ( => 11 => 18 => 9)

If you sort it using ksort, then as a result it will take the following form:

Array ( => 18 => 9 => 11)

I think everything is simple and clear.

krssort($array, $flag);- another php function for sorting an array by key, very similar to the previous one.

The only difference is that it sorts the php array in descending order. That is, it is the antagonist of ksort, just like rsort is for sort.

It also has two input parameters: the array to be sorted and one of the keys. After running it, our example will look like:

Array ( => 11 => 9 => 18)

I think comments are unnecessary 🙂

ukrsort($array, 'function');- an analogue of the previously mentioned php function for sorting an array by key - usort.

It works on the same principle: it preserves the key-value relationship and the php array is sorted according to the user-defined function, the name of which is passed as the second parameter. The first parameter is immutable - it is the array to be sorted.

The difference from usort is that sorting occurs by element keys.

Let's use the following example to illustrate how this function works:

Array ( => 40 => 0 => 10)

For example, we need to sort a php array by key in ascending order. In this case, the custom function would look like this:

Function myCmp($a, $b) ( if ($a == $b) return 0; return $a< $b ? 1: -1; }

As a result, our array will look like this:

array ( => 0 => 10 => 40)

The unequivocal advantage of using this function is that it can be used to sort the php array according to some unusual feature or algorithm.

I remind you that you need to use it only when the keys of the array elements carry some kind of semantic load. Otherwise, it's better to use usort or other simpler functions.

So our article has come to an end (like if you have read this far) 🙂

In it, I tried to describe as simply as possible and at the same time clearly and completely all possible ways of sorting various types of arrays in php, reinforcing my words with examples.

I admit that the publication came out quite voluminous and difficult for a one-time reading. But every time you need php array sort, you can always refer to this article for a description of the function you need and see examples of its use.

I hope the information was useful for you 🙂

Subscribe to project updates and