Home > Article > Backend Development > How to sort and search arrays in PHP
How to sort and search PHP arrays
Overview:
In PHP, an array is a very commonly used data structure used to store and operate a set of related data elements. Sorting and searching arrays are common problems in programming. This article will introduce how to sort and search arrays in PHP, and give corresponding code examples.
1. Array sorting
PHP provides a variety of functions to sort arrays. The following are several commonly used array sorting methods:
$fruits = array("orange", "apple", "banana"); sort($fruits); print_r($fruits);
Output result: Array ([0] => apple [1] => banana [2] => orange )
$fruits = array("orange", "apple", "banana"); rsort($fruits); print_r($fruits);
Output result: Array ([0] => orange [1] => banana [2] => apple )
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); asort($fruits); print_r($fruits);
Output result: Array ( [a] => apple [c] => banana [b] => orange )
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); arsort($fruits); print_r($fruits);
Output result: Array ([b] => orange [c] => banana [a] => apple )
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); ksort($fruits); print_r($fruits);
Output result: Array ( [a] => apple [b] => orange [c] => banana )
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); krsort($fruits); print_r($fruits);
Output result: Array ([c] => banana [b] => orange [a] => apple )
2. Array Search
PHP provides a variety of functions to search arrays. The following are several commonly used array search methods:
$fruits = array("orange", "apple", "banana"); if (in_array("apple", $fruits)) { echo 'Found'; } else { echo 'Not Found'; }
Output result: Found
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); $key = array_search("apple", $fruits); echo "Key: " . $key;
Output result: Key: a
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); if (array_key_exists("b", $fruits)) { echo 'Exists'; } else { echo 'Not Exists'; }
Output result: Exists
$fruits = array("b" => "orange", "a" => "apple", "c" => "banana"); $values = array_values($fruits); print_r($values);
Output result: Array ( [0] => orange [1] => apple [2] => banana )
Summary:
This article introduces the methods of sorting and searching arrays in PHP, and gives corresponding code examples. I hope it will be helpful for beginners to have a deeper understanding and application of PHP array related operations.
The above is the detailed content of How to sort and search arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!