bhylu.com

Advertisements

PHP Null and Empty Values

A missing key, a stored null, an empty string and zero are different states. Choose which ones are valid instead of collapsing all of them with a truthiness check.

How it works

isset returns false for a missing key and for a key whose value is null. array_key_exists can distinguish those cases. The null-coalescing operator supplies a fallback for missing or null values. empty intentionally groups several false-like values, including the string "0", so it is not a universal required-field validator. Define the expected shape and type of incoming data before selecting a convenience operator.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l missing-values.php
php missing-values.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · missing-values.php

<?php
declare(strict_types=1);

$record = ["note" => null, "renewals" => 0];
echo array_key_exists("note", $record) ? "Note key exists\n" : "Missing note\n";
echo isset($record["note"]) ? "Non-null note\n" : "No note value\n";
echo $record["renewals"], " renewals\n";
echo $record["label"] ?? "Unnamed", "\n";

Expected result

Note key exists
No note value
0 renewals
Unnamed

The record deliberately stores null for note, so the key exists even though isset rejects its value. Zero remains a meaningful renewal count. The missing label uses a fallback without an undefined-key notice. These decisions should reflect the data model; a fallback should not quietly hide a missing mandatory identifier.

Check the official PHP manual for detailed version and API contracts.