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";
- Output is Ada, then Inactive. Each => associates a key with a value; the bracket lookup uses that exact key.
- 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";
- Output is 0: Arrays, then 2: Files, then Second item: Files. foreach visits the remaining entries even though key 1 was removed.
- 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.
- 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";
- Output is bool(false), bool(true), then No nickname. The key exists, but its value is null.
- 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