CodeBlanks Logo Icon CodeBlanks

Checking variables with isset() and unset()

PHP course · Beginner · Lesson 11/116

Learn to check a variable's existence with isset() and remove it with unset().

Checking variables with isset()

The isset() function asks whether a variable exists. It returns true if it is defined, false otherwise.

Example: you declared $name = "Alex";. echo isset($name); prints 1 (true appears as 1 with echo).

For an undefined variable, echo isset($missing); prints an empty string (false appears as empty with echo).

This function is handy when you want to check a variable exists before using it.

Removing a variable with unset()

The unset() function completely destroys a variable. After that, no variable with that name exists.

Example: you declared $city = "Berlin";. After unset($city);, $city is gone.

If you then write echo isset($city);, the output is empty; the variable was removed and isset() returns false.

Once you remove a variable with unset(), PHP no longer knows it until you define it again.

Exercise Check a variable with isset

Assign "Berlin" to $city. Write echo "Before: " . isset($city) . "\n";. Then remove it with unset($city). Write echo "After: " . isset($city) . "\n";. Expected output: Before: 1 and After: (empty).

Show example solution
Write the Before line, then unset, then the After line.
Example solution:
<?php
$city = "Berlin";
echo "Before: " . isset($city) . "\n";
unset($city);
echo "After: " . isset($city) . "\n";

Test yourself

  1. What does $name = "Alex"; isset($name) return?

    $name = "Alex";
    echo isset($name);
    • The variable's value: "Alex"
    • true
    • false
    • null
    Show answer

    true — Correct! isset returns true for a defined variable.

  2. Write the function to delete a variable

    ____($city);
    Show answer
    unset($city);
  3. Match each function to its task

    isset()
    asks if it exists
    unset()
    deletes the variable
    echo
    prints the value
    =
    assigns a value
  4. What does $city = "Hamburg"; unset($city); echo isset($city); print?

    $city = "Hamburg";
    unset($city);
    echo isset($city);
    • "Hamburg"
    • 1
    • true
    • empty (prints nothing)
    Show answer

    empty (prints nothing) — Correct! unset removes the variable; isset returns false, echo prints empty.

All lessons in Beginner