CodeBlanks Logo Icon CodeBlanks

Key check with isset()

PHP course · Beginner · Lesson 68/116

Learn to check a key with isset() and the difference from array_key_exists().

Checking keys with isset()

You check whether a key exists in an array with isset(). isset($user["phone"]) returns true if the key exists and its value is not null; otherwise it returns false. No warning is emitted.

For example if a phone number is optional you test with isset first and print it only when present. This avoids the warning from accessing a missing key directly.

null values and key checks

Sometimes a key exists in the array but its value is null. isset() returns false in this case; it treats null values as unset. array_key_exists() only checks that the key exists and returns true for a null value.

Example: with $user = ["phone" => null], isset($user["phone"]) returns false and array_key_exists("phone", $user) returns true. isset is enough for most cases; if the distinction "key set to null on purpose" matters, use array_key_exists.

Exercise Phone check

Create the $user associative array with "name" => "Alex" and "email" => "alex@mail.com". Check the "phone" key with isset(); if it exists print it, otherwise print No phone.

Show example solution
Use the structure if (isset($user["phone"])) { ... } else { echo "No phone\n"; }
Example solution:
<?php
// User and phone check
$user = ["name" => "Alex", "email" => "alex@mail.com"];
if (isset($user["phone"])) {
    echo $user["phone"] . "\n";
} else {
    echo "No phone\n";
}

Test yourself

  1. What is the difference between isset() and array_key_exists()?

    • isset() returns true for a null value, array_key_exists() returns false
    • They are the same
    • isset() checks only numeric keys
    • isset() returns false for a null value, array_key_exists() returns true
    Show answer

    isset() returns false for a null value, array_key_exists() returns true — Correct. isset() returns false for null; array_key_exists() returns true when the key exists.

  2. Complete the isset call

    if (____($user["phone"])) {
        echo $user["phone"];
    }
    Show answer
    if (isset($user["phone"])) {
        echo $user["phone"];
    }
  3. Match each function to its behavior

    isset($a["x"])
    returns false if key missing
    array_key_exists("x", $a)
    returns true if key exists
    $a["x"] ?? "y"
    returns "y" if key missing

All lessons in Beginner