Code with PHP

PHP Array Reference

Core operations for lists and arrays with named keys.

Print this sheet or save it as a PDF using your browser's print menu.

Start with a list and a row

$tags = ['php', 'sqlite'];
$book = ['title' => 'Moon Atlas', 'pages' => 144];
$books = [$book];

Common operations

Read a value
$book['title'] reads the title. Use $book['subtitle'] ?? '' for a fallback when a key is missing or null.
Append to a list
$tags[] = 'pdo'; adds a value at the next integer key.
Check for a key
array_key_exists('pages', $book) checks for the key even if its value is null. isset($book['pages']) also requires a non-null value.
Check for a value
in_array('php', $tags, true) checks for the value with the same type.
Map values
array_map('strtoupper', $tags) returns a transformed array. Passing a single input array preserves its keys.
Filter a list
$filtered = array_filter($tags, fn ($tag) => $tag !== 'php') keeps matching values and their original keys.
Reindex a list
array_values($filtered) resets indexes from zero. Use it before encoding a filtered list as a JSON array.
Extract a column
array_column($books, 'title') returns ['Moon Atlas'].
Sort by value
sort($tags) changes the original array and reindexes it. asort($tags) changes the original and preserves its keys.