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
Release: 2023-03-09 13:02:02
Original
3530 people have browsed it

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   )
Copy after login
  • $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);

?>
Copy after login
rrree

2. Sort the strings in "natural order"

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

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

?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template