Wikis & learning

Read an associative array safely

A settings array gives each value a meaningful key. Optional keys need an explicit fallback when you read them.

A settings array gives each value a meaningful key. Optional keys need an explicit fallback when you read them.

How it works

The null-coalescing operator chooses the fallback if the key is missing or its value is null.

PHP example

<?php
$display = ['theme' => 'light'];
$locale = $display['language'] ?? 'en';
echo $display['theme'] . ' / ' . $locale;

Expected result

light / en

Try a variation

Add language with the value ja. Run again to verify that the stored setting takes precedence.