PHP ships with a huge array library. These are the ones worth memorising.
Transforming
PHP
<?php
$prices = [100, 250, 400];
// map — transform every element
$withVat = array_map(fn($p) => $p * 1.13, $prices);
// filter — keep elements that pass a test
$cheap = array_filter($prices, fn($p) => $p < 300);
// reduce — collapse to a single value
$total = array_reduce($prices, fn($carry, $p) => $carry + $p, 0);
echo $total; // 750array_filter() preserves keys, so the result may have gaps — wrap
it in array_values() if you need a clean list.
Aggregating
PHP
<?php
echo array_sum($prices); // 750
echo array_product([2,3,4]); // 24
echo count($prices); // 3
echo max($prices); // 400
echo min($prices); // 100Searching
PHP
<?php
var_dump(in_array(250, $prices)); // true
var_dump(array_search(250, $prices)); // 1 — the key
print_r(array_unique([1,2,2,3])); // [1,2,3]Like strpos(), array_search() can return 0, so compare with
!== false.
Slicing and splicing
PHP
<?php
$letters = ["a","b","c","d","e"];
print_r(array_slice($letters, 1, 3)); // ["b","c","d"] — non-destructive
array_splice($letters, 1, 2); // removes "b","c" IN PLACE
print_r(array_reverse([1,2,3])); // [3,2,1]
print_r(array_chunk([1,2,3,4,5], 2)); // [[1,2],[3,4],[5]]Stack and queue operations
PHP
<?php
$a = [1,2,3];
array_push($a, 4); // add to end → [1,2,3,4]
array_pop($a); // remove from end → [1,2,3]
array_unshift($a, 0); // add to front → [0,1,2,3]
array_shift($a); // remove front → [1,2,3]Extracting a column
Extremely handy with database rows:
PHP
<?php
$rows = [
["id" => 1, "name" => "Sita"],
["id" => 2, "name" => "Ram"],
];
print_r(array_column($rows, "name")); // ["Sita","Ram"]
print_r(array_column($rows, "name", "id")); // [1 => "Sita", 2 => "Ram"]Custom sorting
PHP
<?php
$books = [
["title" => "B", "price" => 300],
["title" => "A", "price" => 150],
];
usort($books, fn($x, $y) => $x['price'] <=> $y['price']);
// now sorted by price ascending