Computers, Programming
How do I sort the arrays?
Often when solving certain tasks, it is required to sort the data stored in the array. What is the sorting of arrays? Here, for example, playing preference, people lay out their cards by value and suit. This makes it possible to determine what other cards they lack. And in the dictionaries everything is sorted alphabetically. There are many examples. Sorting is the rearrangement of a certain set of objects in some order according to a specified characteristic. Sorting arrays is required quite often. For this, different methods are used. To understand their essence, it is sufficient to consider in detail several ways.
It is important to understand that the array consists of numerous pairs of keys and certain values. Sorting of arrays in the C language is done with the help of dozens of lines of code, and in PHP this is achieved only by one simple command. Arrays can be sorted based on keys or values. You can still distribute the values, leaving them existing keys or assigning new ones.
Main function differences
Sorting of the PHP array is possible using various functions. Let's look at how they differ:
- Some functions sort the arrays by the keys of their elements, and others by the values.
- There is a different sort order: decreasing, increasing, natural, numeric, alphabetic, user-defined or random.
- Some functions are able to save after sorting the connection that exists between the key and the value. But there are functions in which the keys are reset to new values.
- Each function modifies the transferred array. They do not return a sorted copy.
- The sort order is considered undefined when the function defines two elements as equal. This is an unstable sort.
Some functions for sorting arrays in PHP
The sort () and rsort () functions . Sort () arranges the array in alphabetical order. Note that this function is case sensitive. Sorting by values without keys takes place. Rsort () sorts the values in reverse order, and does not take into account the keys.
Asort () is one of the functions that preserves the relationship of keys and values. It is useful to use for associative arrays, when this is important.
Two-dimensional array
It is interesting to sort the two-dimensional array. This can be done in different ways. In PHP, it is possible to compare two numbers or two lines. But in any multidimensional array, each of the elements is an array. In PHP, to compare several arrays, you need to create a specific method. Consider a two-dimensional array in which the abbreviated name of fruit, the full name and price is stored. Elements of an array can be sorted alphabetically by abbreviated names.
Now sorting arrays in PHP will be understandable for you.
Similar articles
Trending Now