CodeBlanks Logo Icon CodeBlanks

Accessing keys

PHP course · Beginner · Lesson 66/116

Learn to access values by key and the behavior for missing keys.

Accessing values by key

You reach a value in an associative array by its key: $user["name"]. The key goes inside square brackets in double quotes. Access reads a value; it does not change the array.

If the key is missing PHP emits a warning and returns null. So you must be careful with unknown keys; the safe way comes in the next step.

The ?? operator (null coalesce)

For safe access to a missing key you use the ?? (null coalesce) operator. $a["x"] ?? "y" returns the value if the key exists and is not null; otherwise it returns "y" on the right. No warning is emitted.

This pattern is handy for configuration and user data: $config["timeout"] ?? 30. You give a default value in a single line.

Exercise Configuration and default theme

Create the $config associative array with theme and lang keys; values dark and en. Print the theme value with echo; use ?? so that if the key were missing the default "light" would appear.

Show example solution
First define the $config array; then write echo ($config["theme"] ?? "light") . "\n";
Example solution:
<?php
// Settings array and default theme
$config = ["theme" => "dark", "lang" => "en"];
echo ($config["theme"] ?? "light") . "\n";

Test yourself

  1. What does the code below print?

    $user = ["name" => "Alex"];
    echo $user["email"] ?? "none";
    • Alex
    • null
    • none
    • email
    Show answer

    none — Correct. The "email" key is missing; ?? gives the right side "none".

  2. Add the default value

    echo $user["email"] ____ "none";
    Show answer
    echo $user["email"] ?? "none";
  3. Match each key to its value

    name
    Alex
    age
    28
    email
    none

All lessons in Beginner