PHP Array Functions
PHP includes a large library of built-in array functions that handle common operations — sorting, searching, merging, filtering, and transforming arrays. Using these functions avoids writing repetitive loops and keeps code clean and readable.
Sorting Arrays
sort() — Sort Indexed Array Ascending
<?php
$prices = [49.99, 12.50, 89.00, 7.25, 34.00];
sort($prices);
print_r($prices);
// Array ( [0] => 7.25 [1] => 12.5 [2] => 34 [3] => 49.99 [4] => 89 )
?>
rsort() — Sort Indexed Array Descending
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
rsort($numbers);
echo $numbers[0]; // Outputs: 9 (highest first)
?>
asort() — Sort Associative Array by Value (Preserve Keys)
<?php
$scores = ["Alice" => 88, "Bob" => 72, "Carol" => 95, "Dave" => 81];
asort($scores);
foreach ($scores as $name => $score) {
echo $name . ": " . $score . "<br>";
}
// Outputs (sorted by score):
// Bob: 72
// Dave: 81
// Alice: 88
// Carol: 95
?>
ksort() — Sort Associative Array by Key
<?php
$inventory = ["banana" => 30, "apple" => 50, "cherry" => 10];
ksort($inventory);
print_r($inventory);
// Array ( [apple] => 50 [banana] => 30 [cherry] => 10 )
?>
Adding and Removing Elements
array_push() — Add to End
<?php
$cart = ["laptop", "mouse"];
array_push($cart, "keyboard", "monitor");
print_r($cart);
// Array ( [0] => laptop [1] => mouse [2] => keyboard [3] => monitor )
?>
array_pop() — Remove from End
<?php
$stack = ["first", "second", "third"];
$removed = array_pop($stack);
echo $removed; // Outputs: third
echo count($stack); // Outputs: 2
?>
array_shift() — Remove from Beginning
<?php
$queue = ["first", "second", "third"];
$served = array_shift($queue);
echo $served; // Outputs: first
echo $queue[0]; // Outputs: second (now the first element)
?>
array_unshift() — Add to Beginning
<?php
$list = ["second", "third"];
array_unshift($list, "first");
echo $list[0]; // Outputs: first
?>
Merging and Slicing
array_merge() — Combine Arrays
<?php
$fruits = ["apple", "banana"];
$veggies = ["carrot", "broccoli"];
$combined = array_merge($fruits, $veggies);
print_r($combined);
// Array ( [0] => apple [1] => banana [2] => carrot [3] => broccoli )
?>
array_slice() — Extract a Portion
<?php
$letters = ["a", "b", "c", "d", "e", "f"];
$portion = array_slice($letters, 2, 3); // Start at index 2, take 3 items
print_r($portion);
// Array ( [0] => c [1] => d [2] => e )
?>
Searching Arrays
in_array() — Check if Value Exists
<?php
$roles = ["admin", "editor", "viewer"];
if (in_array("editor", $roles)) {
echo "Editor role found.";
}
?>
array_search() — Find the Key of a Value
<?php
$colors = ["red", "green", "blue", "yellow"];
$position = array_search("blue", $colors);
echo $position; // Outputs: 2 (index of "blue")
?>
array_key_exists() — Check if Key Exists
<?php
$settings = ["theme" => "dark", "language" => "en"];
if (array_key_exists("theme", $settings)) {
echo "Theme setting: " . $settings["theme"];
}
?>
Transforming Arrays
array_map() — Apply a Function to Each Element
<?php
$prices = [10, 20, 30, 40];
$discounted = array_map(function($price) {
return $price * 0.9; // Apply 10% discount
}, $prices);
print_r($discounted);
// Array ( [0] => 9 [1] => 18 [2] => 27 [3] => 36 )
?>
array_filter() — Keep Only Elements That Pass a Test
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evens = array_filter($numbers, function($n) {
return $n % 2 === 0;
});
print_r($evens);
// Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
?>
array_reduce() — Reduce Array to a Single Value
<?php
$amounts = [100, 250, 75, 300];
$total = array_reduce($amounts, function($carry, $item) {
return $carry + $item;
}, 0); // 0 is the starting value
echo $total; // Outputs: 725
?>
Other Useful Functions
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6];
echo array_sum($numbers); // Outputs: 31 (sum of all elements)
echo count($numbers); // Outputs: 8 (number of elements)
$unique = array_unique($numbers);
print_r($unique);
// Array ( [0] => 3 [1] => 1 [2] => 4 [4] => 5 [5] => 9 [6] => 2 [7] => 6 )
$reversed = array_reverse($numbers);
echo $reversed[0]; // Outputs: 6 (last element is now first)
$flipped = array_flip(["a" => 1, "b" => 2, "c" => 3]);
print_r($flipped);
// Array ( [1] => a [2] => b [3] => c ) — keys and values are swapped
?>
Key Points
sort()andrsort()sort indexed arrays;asort()andksort()sort associative arrays while preserving keys.array_push()andarray_pop()add and remove from the end;array_shift()andarray_unshift()operate on the beginning.array_merge()combines arrays;array_slice()extracts a portion.in_array()checks for a value;array_search()returns the key of a found value.array_map()transforms each element;array_filter()keeps elements that pass a test.array_sum()returns the total;array_unique()removes duplicate values.
