Home >Backend Development >PHP Problem >How to use the sort() function in php (with code examples)

How to use the sort() function in php (with code examples)

autoload
autoloadOriginal
2021-05-06 10:07:283565browse

In

php we often need to operate arrays. Sometimes we may need to sort the array. In this case, we need to use the built-in function sort() in php. This article will take you to take a look.

sort    ( array $array   , int $sort_flags = SORT_REGULAR   )
  • $array: The array to be sorted.

  • $sort_flags: The optional second parameter $sort_flags can change the behavior of sorting with the following values: SORT_REGULAR - normal comparison of cells; SORT_NUMERIC - cells are compared as numbers; SORT_STRING - Cells are compared as strings; SORT_LOCALE_STRING - Cells are compared as strings according to the current locale setting, which can be changed with setlocale(). SORT_NATURAL - Like natsort(), sorts strings in "natural order" per unit. SORT_FLAG_CASE - can be combined with SORT_STRING or SORT_NATURAL (OR bitwise operation) to sort strings in a case-insensitive manner.

  • Return value: Return true on success, or return false on failure.

Code example

1. Normal comparison unit

<?php

$arr=array("a"=>"c张三","c"=>"b李四","b"=>"a王五");
sort($arr);
print_r($arr);

?>
rrree

2. Sort the strings in "natural order"

输出;Array ( [0] => a王五 [1] => b李四 [2] => c张三 )
<?php

$arr=array("a"=>"A张三","c"=>"b李四","b"=>"a王五");
sort($arr, SORT_NATURAL | SORT_FLAG_CASE);
print_r($arr);

?>

Recommended: 2021 PHP Interview Questions Summary (Collection)》《php video tutorial

The above is the detailed content of How to use the sort() function in php (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn