Skip to content
← Back to Snippets
Code

Avoid Null Coalescing with Explicit Defaults

Demonstrates explicit isset() branches for default values instead of using the null coalescing operator.

Purpose

Demonstrates explicit isset() branches for default values instead of using the null coalescing operator.

Snippet details

ContextRequestLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Avoid Null Coalescing with Explicit Defaults.
 *
 * Purpose:
 * Uses clear isset() branches to choose defaults.
 *
 * @param array $settings Settings array.
 * @return array Normalized settings.
 */
function ogSnippetAvoidNullCoalescingWithExplicitDefaults(array $settings): array {
	$timezone = 'UTC';
	$theme = 'dark';

	if (isset($settings['timezone']) === true) {
		$timezone_value = trim((string) $settings['timezone']);

		if ($timezone_value !== '') {
			$timezone = $timezone_value;
		}
	}

	if (isset($settings['theme']) === true) {
		$theme_value = trim((string) $settings['theme']);

		if ($theme_value !== '') {
			$theme = $theme_value;
		}
	}

	return array(
		'timezone' => $timezone,
		'theme' => $theme
	);
}

$settings = ogSnippetAvoidNullCoalescingWithExplicitDefaults(array('theme' => 'gold-command'));

echo 'Explicit default theme: '.$settings['theme'];