With the rapid development of PHP, more and more people are using it. In the PHP array learning excerpt, I learned about the establishment of the most basic PHP array and the display of array elements. You need to learn more about PHP Array Operations. The first issue is PHP array sorting and descending sorting.
Quickly create an array function range ()
- For example, the range () function can quickly create a number array from 1 to 9:
- <?Php
- $Numbers=Range(1, 9 );
- Echo $ numbers [1];
- ?>
Of course, range (9, 1) is used to create a number array from 9 to 1. At the same time, range () can also create a character array from a to z:
- <?php
- $numbers=range(a,z);
- foreach ($numbers as $mychrs)
- echo $mychrs." ";
- ?>
Note the case sensitivity when using character arrays. For example, range (A, z) and range (a, Z) are different. The range () function also has a third parameter, which is used to set the step size. For example, the array elements created by range (, 3) are: 1, 4, and 7. Common PHP array sorting: elements in an array are represented by characters or numbers. Therefore, you can sort array elements in ascending order. This function is sort (). For example:
- <?Php
- $People=Array('Name', 'sex', 'nation', 'birth ');
- Foreach ($ people as $ mychrs)
- Echo $ mychrs ."";
- Sort ($ people );
- Echo"<Br />--- After sorting ---<Br />";
- Foreach ($ people as $ mychrs)
- Echo $ mychrs ."";
- ?>
The array elements in ascending order are displayed as birth name nation sex. Of course, the sort () function is case-sensitive (the order of letters from large to small is:... Z... A... Z)
The Sort () function also has a second parameter, which indicates whether the PHP array sorting ascending rule is used to compare numbers or strings. For example:
- <?Php
- Echo "--- sort by numbers in ascending order ---<Br />";
- $Num2=Array('26', '3 ',);
- Sort ($ num2, SORT_NUMERIC );
- Foreach ($ num2 as $ mychrs)
- Echo $ mychrs ."";
- Echo"<Br />--- Sort by character in ascending order ---<Br />";
- $Num3=Array('26', '3 ');
- Sort ($ num3, SORT_STRING );
- Foreach ($ num3 as $ mychrs)
- Echo $ mychrs ."";
- ?>
SORT_NUMERIC and SORT_STRING are used to declare the ascending order of numbers or characters. If the numbers are listed in ascending order: 3, 26, but if the characters are listed in ascending order, they are listed as 26, 3. In PHP, in addition to the ascending function, there are also descending or inverse sort functions, which are rsort () functions, such as: $ num1 = range (); rsort ($ num1 ); this is actually equivalent to range (9, 1 ).