PHP Array Functions
In this page:
Getting Array Length
PHP ships with well over a hundred built-in array functions, covering everything from transforming values to filtering, combining, and inspecting arrays — knowing the common ones saves you from hand-writing loops for routine tasks.
Example: Getting Array Length
<?php
$fruits = ["apple", "banana", "cherry"];
echo count($fruits);
?>
Login to try C/C++/Java/PHP code in the editor
Merging Arrays
array_map() applies a given function to every element of an array and returns a new array of the results, which is the idiomatic way to transform a whole list at once, like doubling every number or uppercasing every string.
Example: Merging Arrays
<?php
$numbers = [1, 2, 3];
$doubled = array_map(function ($n) {
return $n * 2;
}, $numbers);
print_r($doubled);
?>
Login to try C/C++/Java/PHP code in the editor
Getting Keys and Values
array_filter() keeps only the elements that satisfy a callback function, returning a new array with the rest removed — useful for tasks like extracting only the active users from a full user list.
Example: Getting Keys and Values
<?php
$users = [
["name" => "Alice", "active" => true],
["name" => "Bob", "active" => false],
];
$activeUsers = array_filter($users, function ($u) {
return $u["active"];
});
print_r($activeUsers);
?>
Login to try C/C++/Java/PHP code in the editor
Filtering Arrays
array_reduce() collapses an array down to a single value by repeatedly applying a callback that combines an accumulator with each element, which is how you'd compute something like a running total or a concatenated string from a list.
Example: Filtering Arrays
<?php
$numbers = [1, 2, 3, 4];
$total = array_reduce($numbers, function ($carry, $n) {
return $carry + $n;
}, 0);
echo $total;
?>
Login to try C/C++/Java/PHP code in the editor
Mapping Array Elements
in_array() and array_key_exists() check for a value or a key respectively, and it's easy to confuse them — in_array() searches the values, array_key_exists() searches the keys, and mixing them up is a common source of bugs.
Example: Mapping Array Elements
<?php
$fruits = ["apple", "banana"];
var_dump(in_array("apple", $fruits));
$person = ["name" => "Alice"];
var_dump(array_key_exists("name", $person));
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: