Home > Article > Daily Programming > How to sort array in php
PHP To sort an array, you need to master the sort function in PHP. The sort function represents sorting an array. The sort function can not only sort numeric arrays, but also sort string arrays.
Below we will introduce you to PHP's method of sorting string arrays and array arrays through simple code examples.
1. Sort the string array
The code is as follows:
<?php $text = array("Python","Java","Banana","PHP","Apple"); //对字符串数组进行排序 echo "<pre class="brush:php;toolbar:false">"; sort($text); print_r($text);
The sorting result is as follows:
As shown in the figure, sorted in alphabetical order.
2. Sort the digital array
<?php $numbers = array(5, 10, 3.5, 1, 8, 2); //对数字数组进行排序 echo "<pre class="brush:php;toolbar:false">"; sort($numbers); print_r($numbers);
The sorting results are as follows:
As shown in the figure, press the numbers Sort by size.
sort function means sorting the array. Once this function is complete, the elements will be arranged from lowest to highest.
sort syntax:
bool sort (array &$array [,int $sort_flags= SORT_REGULAR ])
The parameters:
array represents the input array.
sort_flags is an optional second parameter, sort_flags can be used to modify the sorting behavior using the following values:
Sort type flags:
SORT_REGULAR - Compare items normally (don't change types)
SORT_NUMERIC - Compare items as numbers
SORT_STRING - Compare items as strings
SORT_LOCALE_STRING - Compare items as characters according to the current locale Strings are compared. It uses a locale, which can be changed using setlocale()
SORT_NATURAL - Uses a "natural ordering" to compare items as strings, like natsort()
SORT_FLAG_CASE - Can be combined with (or bitwise) SORT_STRING Or SORT_NATURAL to sort strings case-insensitively
This article is a detailed introduction to sorting arrays in PHP. I hope it will be helpful to friends in need!
The above is the detailed content of How to sort array in php. For more information, please follow other related articles on the PHP Chinese website!