Array Functions
Add, remove and inspect array items with built-in functions.
Syntax
array_push($array, $value);PHP provides many functions for working with arrays:
count()— number of elements.array_push()/array_pop()— add / remove from the end.in_array()— check if a value exists.array_keys()/array_values()— get keys or values.array_merge()— combine arrays.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Use array_map() to convert an array of prices from dollars to cents before saving to the database.
- Filter a list of users with array_filter() to extract only those with an active subscription.
- Merge two configuration arrays with array_merge() where the second overrides the first.
More examples
array_map transforms values
array_map() applies a callback to every element and returns a new array, leaving the original unchanged.
<?php
$prices = [9.99, 24.99, 4.49];
$cents = array_map(fn($p) => (int) round($p * 100), $prices);
print_r($cents); // [999, 2499, 449]array_filter removes elements
array_filter() keeps elements for which the callback returns true; array_values() re-indexes the result.
<?php
$users = [
['name' => 'Alice', 'active' => true],
['name' => 'Bob', 'active' => false],
['name' => 'Carol', 'active' => true],
];
$active = array_values(
array_filter($users, fn($u) => $u['active'])
);
echo count($active); // 2array_merge and array_unique
array_merge() combines arrays with later values winning on duplicate string keys; array_unique() deduplicates values.
<?php
$defaults = ['debug' => false, 'cache' => true, 'timeout' => 30];
$custom = ['debug' => true, 'timeout' => 60];
$config = array_merge($defaults, $custom);
// debug => true, cache => true, timeout => 60
$tags = array_unique(['php', 'web', 'php', 'backend']);
print_r($tags); // php, web, backend
Discussion