Codectionary / Developer documentation / PHP

PHP Arrays

A PHP array is an ordered map: every value has an integer or string key. A list literal starts with keys 0, 1, 2; named keys can describe a record. Removing an item does not automatically renumber the remaining keys. Run these examples with PHP CLI; their output is plain text.

Syntax

$topics = ["Arrays", "Functions"];
$profile = ["name" => "Ada"];
echo $topics[0], "\n";
echo $profile["name"], "\n";

Examples

Use named keys to describe a record

Read a profile by field name and make its boolean state explicit in the output.

<?php
$profile = ["name" => "Ada", "active" => false];
echo $profile["name"], "\n";
echo $profile["active"] ? "Active\n" : "Inactive\n";
  1. Output is Ada, then Inactive. Each => associates a key with a value; the bracket lookup uses that exact key.
  2. The conditional selects a readable label. Echoing false directly produces an empty string, which would hide the distinction between inactive and missing output.

Remove a list item without assuming new indexes

unset removes a key. array_values creates a new list with consecutive integer keys when that is what the next operation needs.

<?php
$topics = ["Arrays", "Functions", "Files"];
unset($topics[1]);
foreach ($topics as $index => $title) {
    echo "$index: $title\n";
}
$topics = array_values($topics);
echo "Second item: ", $topics[1], "\n";
  1. Output is 0: Arrays, then 2: Files, then Second item: Files. foreach visits the remaining entries even though key 1 was removed.
  2. array_values returns a reindexed array, so assigning it back gives Files key 1. Use it for lists, not records whose meaningful keys you need to preserve.
  3. If you remove key 0 instead, predict which original keys foreach prints before the reindexing step.

Tell a missing key apart from a null value

isset answers whether a key has a non-null value. array_key_exists answers whether the key exists at all.

<?php
$profile = ["nickname" => null];
var_dump(isset($profile["nickname"]));
var_dump(array_key_exists("nickname", $profile));
echo $profile["nickname"] ?? "No nickname", "\n";
  1. Output is bool(false), bool(true), then No nickname. The key exists, but its value is null.
  2. The ?? operator uses the fallback for either an absent key or a null value. It preserves legitimate false, 0 and empty-string values; it is not a general test for truthiness.

Best practices

  • Use foreach for visiting entries; count does not tell you which integer keys exist after deletions.
  • Decide whether null means a present-but-empty value before choosing isset, array_key_exists or ??.
  • Do not mix numeric-looking string identifiers with integer keys without checking PHP key conversion rules.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading