Skip to content
← Back to Snippets
Code

The Difference Between isset() and empty()

Compares isset(), empty(), and array_key_exists() across common values so missing keys, nulls, zeroes, and blank strings are handled intentionally.

Purpose

Compares isset(), empty(), and array_key_exists() across common values so missing keys, nulls, zeroes, and blank strings are handled intentionally.

Snippet details

ContextArrayLevelPracticalCopy-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.
 */

/**
 * The Difference Between isset() and empty().
 *
 * Purpose:
 * Shows how isset(), empty(), and array_key_exists() report different results
 * for missing, null, blank, zero, and filled values.
 *
 * @param array $values Values to inspect.
 * @param array $keys Keys to compare.
 * @return array Inspection rows for each key.
 */
function ogSnippetIssetVsEmpty(array $values, array $keys): array {
	$rows = array();

	foreach ($keys as $key) {
		$key = (string) $key;
		$value_preview = '[missing]';

		if (array_key_exists($key, $values) === true) {
			$value_preview = var_export($values[$key], true);
		}

		$rows[] = array(
			'key' => $key,
			'value' => $value_preview,
			'isset' => isset($values[$key]),
			'empty' => empty($values[$key]),
			'array_key_exists' => array_key_exists($key, $values)
		);
	}

	return $rows;
}

$ship_status = array(
	'enterprise' => 'online',
	'serenity' => '',
	'galactica' => 0,
	'nostromo' => null
);

$status_rows = ogSnippetIssetVsEmpty(
	$ship_status,
	array('enterprise', 'serenity', 'galactica', 'nostromo', 'rocinante')
);

foreach ($status_rows as $status_row) {
	$line = $status_row['key'].' isset=';

	if ($status_row['isset'] === true) {
		$line .= 'true';
	} else {
		$line .= 'false';
	}

	$line .= ' empty=';

	if ($status_row['empty'] === true) {
		$line .= 'true';
	} else {
		$line .= 'false';
	}

	echo $line."\n";
}