Sorting and Searching Arrays
Use sort, usort, array_search, and in_array.
Sorting and Searching Arrays is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Sort?
PHP provides a rich set of sorting and searching functions for arrays. Choose the right one based on whether you want to preserve keys, sort by value or key, or use a custom comparator.
sort() and rsort()
sort() sorts by value ascending (re-indexes); rsort() sorts descending:
<?php
$nums = [3, 1, 4, 1, 5, 9, 2, 6];
sort($nums);
print_r($nums); // [1, 1, 2, 3, 4, 5, 6, 9]
$letters = ['c', 'a', 'b'];
rsort($letters);
print_r($letters); // ['c', 'b', 'a']asort() and arsort()
asort() sorts by value but preserves keys — useful for associative arrays:
<?php
$scores = ['Alice' => 85, 'Bob' => 92, 'Carol' => 78];
asort($scores);
print_r($scores);
// ['Carol'=>78, 'Alice'=>85, 'Bob'=>92]ksort() and krsort()
ksort() sorts by keys ascending; krsort() descending:
<?php
$data = ['banana' => 2, 'apple' => 5, 'cherry' => 1];
ksort($data);
print_r($data);
// ['apple'=>5, 'banana'=>2, 'cherry'=>1]usort() — Custom Comparator
usort() sorts with a user-defined comparison function:
<?php
$people = [
['name' => 'Charlie', 'age' => 25],
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 20],
];
usort($people, fn($a, $b) => $a['age'] <=> $b['age']);
foreach ($people as $p) echo $p['name'] . ' '; // Bob Charlie Alicein_array() — Value Search
in_array() checks whether a value exists in an array:
<?php
$tags = ['php', 'mysql', 'nginx'];
var_dump(in_array('php', $tags)); // true
var_dump(in_array('apache', $tags)); // false
// Third argument = strict mode (uses ===)
var_dump(in_array('1', [1, 2, 3], true)); // false (type mismatch)array_search() — Return Key
array_search() returns the key of the first matching value, or false:
<?php
$colors = ['red', 'green', 'blue'];
$key = array_search('green', $colors);
echo $key; // 1
$notFound = array_search('purple', $colors);
var_dump($notFound); // bool(false)array_unique()
Remove duplicate values from an array:
<?php
$ids = [1, 2, 2, 3, 3, 3, 4];
$unique = array_unique($ids);
print_r($unique); // [1, 2, 3, 4] — keys preserved!
$reindexed = array_values($unique); // re-index to 0,1,2,3array_flip()
Swap keys and values in an associative array:
<?php
$map = ['a' => 1, 'b' => 2, 'c' => 3];
$flipped = array_flip($map);
print_r($flipped); // [1=>'a', 2=>'b', 3=>'c']
// Useful for O(1) lookup by value
$exists = isset($flipped[2]); // truearray_diff() and array_intersect()
Compare arrays to find differences and overlaps:
<?php
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];
$diff = array_diff($a, $b); // [1, 2] — in a but not b
$inter = array_intersect($a, $b); // [3, 4, 5] — in both
print_r($diff);
print_r($inter);Binary Search via Custom Logic
PHP doesn't have a built-in binary search, but you can implement one or use sorted keys for fast lookups:
<?php
function binarySearch(array $arr, int $target): int {
$lo = 0;
$hi = count($arr) - 1;
while ($lo <= $hi) {
$mid = intdiv($lo + $hi, 2);
if ($arr[$mid] === $target) return $mid;
$arr[$mid] < $target ? $lo = $mid + 1 : $hi = $mid - 1;
}
return -1;
}
echo binarySearch([1,3,5,7,9], 7); // 3Quick Check
Which PHP function returns the key of a matching value in an array?
Recap: Sorting and Searching
Key functions:
sort/rsort— by value, re-indexasort/arsort— by value, keep keysksort/krsort— by keyusort— custom comparatorin_array— value existence checkarray_search— value to key lookuparray_unique/array_flip/array_diff/array_intersect
Frequently asked questions
Is the “Sorting and Searching Arrays” lesson free?
Yes — the full text of “Sorting and Searching Arrays” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Sorting and Searching Arrays”?
Use sort, usort, array_search, and in_array. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sorting and Searching Arrays” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Indexed and Associative Arrays
- Multidimensional Arrays
- Sorting and Searching Arrays
- Array Transformation Functions