PHP Arrays

PHP arrays store many values in one variable. They are ordered maps, so the same structure works as a list, a dictionary or a nested data tree. Arrays are probably the most used feature in PHP.

Indexed Arrays

Use square brackets to create an array. $array[] = value appends to the end.

<?php
$langs = ['PHP', 'JavaScript', 'Python'];
$langs[] = 'Go';
echo $langs[0], "\n";
echo count($langs), "\n";
echo end($langs);
PHP
4
Go

Associative Arrays

Associative arrays use named keys, much like an object or dictionary.

<?php
$user = [
    'name' => 'Hina',
    'email' => 'hina@example.com',
    'role' => 'editor',
];
$user['role'] = 'admin';
unset($user['email']);
print_r($user);
var_dump(array_key_exists('email', $user));
Array
(
    [name] => Hina
    [role] => admin
)
bool(false)

Multidimensional Arrays

<?php
$products = [
    ['name' => 'Rice', 'price' => 3.2],
    ['name' => 'Tea', 'price' => 5.0],
];
foreach ($products as $p) {
    echo "{$p['name']}: {$p['price']}\n";
}
echo $products[1]['name'];
Rice: 3.2
Tea: 5
Tea

Sorting PHP Arrays

  • sort / rsort: sort values, reindex keys
  • asort / arsort: sort by value, keep keys
  • ksort / krsort: sort by key
  • usort: sort with your own comparison function
<?php
$scores = ['ali' => 70, 'sara' => 92, 'omar' => 85];
arsort($scores);
print_r($scores);

$people = [['n' => 'Zara', 'a' => 30], ['n' => 'Adil', 'a' => 25]];
usort($people, fn($x, $y) => $x['a'] <=> $y['a']);
echo $people[0]['n'];
Array
(
    [sara] => 92
    [omar] => 85
    [ali] => 70
)
Adil

Useful Array Functions

array_map transforms each item, array_filter keeps items that pass a test, and array_reduce combines items into one value. in_array and array_search find values.

<?php
$nums = [1, 2, 3, 4, 5, 6];
$even = array_filter($nums, fn($n) => $n % 2 === 0);
$squares = array_map(fn($n) => $n ** 2, $even);
$total = array_reduce($squares, fn($c, $n) => $c + $n, 0);
echo implode(",", $squares), " total=$total\n";
var_dump(in_array(4, $nums, true));
[$first, $second] = $nums;
echo $first + $second;
4,16,36 total=56
bool(true)
3

Frequently asked questions

How do I add an element to an array in PHP?

Use $array[] = $value to append, $array["key"] = $value for a named key, or array_push() / array_unshift() for the end or start.

How do I check if a value exists in a PHP array?

Use in_array($value, $array, true) for values and array_key_exists() or isset() for keys.

Why does array_filter keep the original keys?

array_filter preserves keys, so the result may have gaps. Wrap it in array_values() if you need a clean 0-based list.

How do I print an array in PHP?

Use print_r() for a readable view, var_dump() for types, or json_encode() for a JSON string.