PHP has an enormous built-in array function library — over 80 functions. This lesson covers the handful that come up in almost every real script; the full array function reference is on php.net.
Applies a function to every element and returns a new array of the results:
<?php
$prices = [100, 200, 300];
$withTax = array_map(fn($p) => $p * 1.18, $prices);
print_r($withTax); // [118, 236, 354]
?>Keeps only the elements that pass a test:
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even); // [1 => 2, 3 => 4, 5 => 6] — note the original indexes stick around
?><?php
$fruits = ["apple", "banana", "mango"];
var_dump(in_array("banana", $fruits)); // true
var_dump(array_search("mango", $fruits)); // 2 (its index)
?>| Function | What it does |
|---|---|
| sort($arr) | Sorts values ascending, re-indexes from 0 |
| rsort($arr) | Sorts values descending, re-indexes from 0 |
| asort($arr) | Sorts values ascending, keeps original keys |
| ksort($arr) | Sorts by key instead of value |
<?php
$scores = [40, 10, 30, 20];
sort($scores);
print_r($scores); // [10, 20, 30, 40]
?>sort() modifies in place
Sorting functions like sort() modify the array in place and don't return the sorted array — they return true/false for success. Assigning their result to a variable is a common beginner mistake.
<?php
$a = ["red", "green"];
$b = ["blue", "yellow"];
$all = array_merge($a, $b);
print_r($all); // ["red", "green", "blue", "yellow"]
?>