← Back to PHP Course | Chapter 7: Arrays | Lesson 10 of 13

PHP Array Functions

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
<?php
$fruits = ["apple", "banana", "cherry"];
echo count($fruits);
?>

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
<?php
$numbers = [1, 2, 3];
$doubled = array_map(function ($n) {
    return $n * 2;
}, $numbers);
print_r($doubled);
?>

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
<?php
$users = [
    ["name" => "Alice", "active" => true],
    ["name" => "Bob", "active" => false],
];
$activeUsers = array_filter($users, function ($u) {
    return $u["active"];
});
print_r($activeUsers);
?>

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
<?php
$numbers = [1, 2, 3, 4];
$total = array_reduce($numbers, function ($carry, $n) {
    return $carry + $n;
}, 0);
echo $total;
?>

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
<?php
$fruits = ["apple", "banana"];
var_dump(in_array("apple", $fruits));

$person = ["name" => "Alice"];
var_dump(array_key_exists("name", $person));
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.