CodeBlanks Logo Icon CodeBlanks

Reading from a session

PHP course · Intermediate · Lesson 84/115

Learn to read data from $_SESSION and check existence with isset().

Reading data from $_SESSION

You read session data with $_SESSION['key']. But if the key is missing, PHP raises a warning. To avoid this, check existence with isset().

If isset($_SESSION['lang']) returns true, the key is defined and safe to read. If false, it is undefined; use a default value.

Tip: $_SESSION['lang'] ?? 'en' (null coalescing) gives you both the check and a default in one line.

Defaults for missing keys

When reading from a session, a key may be undefined. Two common approaches: an if/else with isset(), or the null coalescing operator ??.

$lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'en'; is the classic ternary form. Shorter: $lang = $_SESSION['lang'] ?? 'en';

Both do the same: if undefined, return 'en'; otherwise the stored value. The short form is preferred in modern PHP 8.

Exercise Read a default language from a missing key

Call session_start(). With if/else, check isset($_SESSION['lang']): if defined, assign the stored value to $lang; otherwise assign 'en'. Then echo $lang.

Show example solution
Call session_start, use if(isset($_SESSION['lang'])) to set $lang from the session, else 'en', then echo $lang.
Example solution:
<?php
// Print the default language if $_SESSION['lang'] is missing
session_start();
if (isset($_SESSION['lang'])) {
    $lang = $_SESSION['lang'];
} else {
    $lang = 'en';
}
echo $lang . "\n";

Test yourself

  1. Complete the isset key check

    <?php
    session_start();
    $_SESSION['count'] = 5;
    if (____ && $_SESSION['count'] > 0) {
        echo 'ok';
    } else {
        echo 'en';
    }
    
    Show answer
    <?php
    session_start();
    $_SESSION['count'] = 5;
    if (isset($_SESSION['lang']) && $_SESSION['count'] > 0) {
        echo 'ok';
    } else {
        echo 'en';
    }
    
  2. What does isset($_SESSION['missing']) return?

    • true
    • 1
    • false
    • null
    Show answer

    false — Correct. When the key is undefined, isset returns false.

  3. Match the session reading tools

    isset($_SESSION['k'])
    Checks if key exists
    $_SESSION['k']
    Reads the value
    ?? 'default'
    Gives default if undefined
    empty()
    Checks if empty

All lessons in Intermediate