PHP NULL

La Lakshmi Priya Updated 29 Oct 2026
11 min read

What Is NULL?

In simple terms: null means "no value". It represents the absence of data — not zero, not an empty string, but nothing at all.

Technically: null is a special type that has exactly one value, also written null. A variable holds null when it has been explicitly assigned null, when it has been unset, or when it has never been assigned (in which case reading it also raises a warning).

Why NULL Exists

Real data is often incomplete:

  • A customer may not have a middle name or a second phone number.
  • An order may not have a delivery date yet.
  • A database column may contain no value.
  • A search may find no matching record.

Using 0 or "" for "unknown" is ambiguous: a discount of 0 is different from "no discount defined", and an empty name is different from "name not provided". null represents "missing" explicitly, so code can distinguish it from real values.


Creating NULL Values

Syntax

$variable = null;

Example

<?php
$deliveryDate = null;
$couponCode = NULL;

var_dump($deliveryDate);
var_dump($couponCode);

Output

NULL
NULL

null is case-insensitive (NULL, Null, and null are the same), but the lowercase form is the standard in modern code.


When a Value Becomes NULL

A value can be null for several reasons. Recognizing each source helps you debug unexpected null values.

1. Explicit Assignment

$middleName = null;

2. After unset()

<?php
$sessionToken = "abc123";
unset($sessionToken);

var_dump($sessionToken ?? null);

Output

NULL

After unset(), the variable no longer exists. Reading it directly would raise an "Undefined variable" warning; the ?? operator (explained below) reads it safely.

3. Reading an Undefined Variable or Array Key

<?php
$user = ['name' => 'Asha'];

$email = $user['email'];
var_dump($email);

Output

PHP Warning:  Undefined array key "email" in /path/script.php on line 4
NULL

PHP raises a warning and uses null. The warning is a signal of a bug or of missing data that should be handled explicitly.

4. A Function That Does Not Return a Value

<?php
function logMessage(string $message)
{
    echo "[LOG] $message\n";
}

$result = logMessage("Started");
var_dump($result);

Output

[LOG] Started
NULL

A function without a return statement (or with a bare return;) returns null.

5. Functions That Return NULL for "Not Found"

Some functions return null to signal that nothing was found or that input was invalid:

<?php
$data = json_decode('{"name": "Ravi"}', true);

var_dump($data['age'] ?? null);
var_dump(array_key_last([]));

Output

NULL
NULL

array_key_last() returns null for an empty array, because an empty array has no last key.


Checking for NULL

CheckReturns true WhenWarning If Variable Is Undefined?
$x === nullThe value is nullYes
is_null($x)The value is nullYes
isset($x)The variable exists and is not nullNo
empty($x)The variable does not exist or is falsy (including null, 0, "", "0", [])No

Example

<?php
$phone = null;
$email = "";
$age = 0;

var_dump($phone === null);   // bool(true)
var_dump($email === null);   // bool(false) — empty string is not null
var_dump($age === null);     // bool(false) — zero is not null

var_dump(isset($phone));     // bool(false)
var_dump(isset($email));     // bool(true)

var_dump(empty($phone));     // bool(true)
var_dump(empty($age));       // bool(true)

Choosing the Right Check

  • Use === null when the variable definitely exists and you need to know whether it holds null. It is clear and fast. is_null() does the same thing but is a function call.
  • Use isset() when the variable or array key might not exist — for example, optional form fields or optional configuration keys. It does not raise warnings.
  • Use empty() only when 0, "", and "0" should be treated as "missing" too. It is often too broad.

isset() Cannot Distinguish "Null" From "Missing"

<?php
$settings = ['theme' => null];

var_dump(isset($settings['theme']));               // bool(false)
var_dump(array_key_exists('theme', $settings));    // bool(true)

isset() returns false for a key that exists with a null value. If the difference matters — for example, "the user explicitly cleared this setting" versus "this setting was never configured" — use array_key_exists().


The Null Coalescing Operator ??

What It Does

$a ?? $b returns $a if it exists and is not null; otherwise it returns $b. It does not raise warnings for undefined variables or keys.

Example

<?php
$query = ['page' => '3'];

$page = $query['page'] ?? '1';
$sort = $query['sort'] ?? 'newest';

echo "Page: $page, Sort: $sort";

Output

Page: 3, Sort: newest

Why It Is Useful

Before PHP 7, the same logic required:

$sort = isset($query['sort']) ? $query['sort'] : 'newest';

?? expresses "use this value, or a default if it is missing" in one short, readable expression. It is the standard way to read optional input from $_GET, $_POST, configuration arrays, and decoded JSON.

Chaining

<?php
$userName = null;
$guestName = null;

echo $userName ?? $guestName ?? 'Anonymous';

Output

Anonymous

PHP checks each value from left to right and returns the first one that is not null.

?? vs ?:

OperatorFalls Back When the Left Side IsWarning for Undefined Variable?
??null or undefinedNo
?:Any falsy value (null, 0, "", "0", false, [])Yes
<?php
$quantity = 0;

echo $quantity ?? 1;  // 0 — zero is a real value
echo "\n";
echo $quantity ?: 1;  // 1 — zero is falsy

Output

0
1

Use ?? when 0, "", and false are valid values that must be kept. The Null Coalescing Operator lesson covers this operator in depth.


The Null Coalescing Assignment Operator ??=

$a ??= $b assigns $b to $a only if $a is null or undefined (PHP 7.4+).

<?php
$config = ['timeout' => 30];

$config['timeout'] ??= 60;
$config['retries'] ??= 3;

print_r($config);

Output

Array
(
    [timeout] => 30
    [retries] => 3
)

timeout already has a value, so it is kept. retries was missing, so the default is assigned. This is a concise way to fill in default settings.


The Nullsafe Operator ?-> (PHP 8.0+)

When working with objects, a method or property may return null. Calling a method on null causes a fatal error. The nullsafe operator stops the chain and returns null instead.

<?php
class Address
{
    public function __construct(public string $city) {}
}

class Customer
{
    public function __construct(public ?Address $address = null) {}
}

$withAddress = new Customer(new Address("Madurai"));
$withoutAddress = new Customer();

echo $withAddress->address?->city ?? 'Unknown', "\n";
echo $withoutAddress->address?->city ?? 'Unknown', "\n";

Output

Madurai
Unknown

How It Works

  • ?Address declares that the property may contain an Address object or null.
  • For the second customer, address is null, so ?->city stops and returns null instead of throwing an error.
  • ?? 'Unknown' provides a readable fallback.

Without ?->, accessing $withoutAddress->address->city would produce a warning ("Attempt to read property "city" on null"), and calling a method on null would be a fatal Error. The Nullsafe Operator lesson covers this in detail.


Nullable Types

Type declarations can allow null explicitly with a ? prefix or a union with null.

Example

<?php
function formatName(string $first, ?string $middle, string $last): string
{
    if ($middle === null) {
        return "$first $last";
    }

    return "$first $middle $last";
}

echo formatName("Sita", null, "Raman") . "\n";
echo formatName("Sita", "Devi", "Raman") . "\n";

Output

Sita Raman
Sita Devi Raman

Explanation

  • ?string means "a string or null". Writing string|null (PHP 8.0+) means the same.
  • Passing null to a parameter declared as plain string would throw a TypeError for user-defined functions.
  • Making null part of the type forces you to think about — and handle — the missing case explicitly.

Nullable Return Types

<?php
function findProductName(int $id): ?string
{
    $products = [1 => 'Keyboard', 2 => 'Monitor'];

    return $products[$id] ?? null;
}

$name = findProductName(5);

echo $name === null ? "Product not found" : $name;

Output

Product not found

Returning null for "not found" is a common, readable convention. Callers must check the result before using it, and the ?string return type tells them so.

Version note: In PHP 8.4, declaring a parameter with a null default but without a nullable type — function f(string $x = null) — is deprecated. Write ?string $x = null instead.


NULL in Operations

When null is used in calculations or string operations, PHP converts it automatically.

<?php
$bonus = null;

var_dump(1000 + $bonus);
var_dump("Total: " . $bonus . "!");
var_dump((int) null, (string) null, (bool) null);
var_dump((array) null);

Output

int(1000)
string(8) "Total: !"
int(0)
string(0) ""
bool(false)
array(0) {
}
ConversionResult
To integer or float0
To string"" (empty string)
To booleanfalse
To array[] (empty array)

These conversions mean that a missing value can silently become 0 or "" in a calculation, hiding a bug. When a value may be null, handle it explicitly (for example, with ?? 0) so the intent is clear.

Passing NULL to Built-in Functions (PHP 8.1+)

<?php
$comment = null;

echo strlen($comment);

Output

PHP Deprecated:  strlen(): Passing null to parameter #1 ($string) of type string is deprecated
0

Since PHP 8.1, passing null to a non-nullable parameter of a built-in function triggers a deprecation notice. This behavior is planned to become a TypeError in a future major version. Values from databases and optional inputs are the usual cause.

Fix: convert explicitly where null is expected:

<?php
echo strlen($comment ?? '');

Comparing NULL With ==

Loose comparisons with null follow PHP's conversion rules and are easy to misread.

<?php
var_dump(null == false);  // bool(true)
var_dump(null == 0);      // bool(true)
var_dump(null == "");     // bool(true)
var_dump(null == []);     // bool(true)
var_dump(null == "0");    // bool(false)
var_dump(null === null);  // bool(true)

Why null == "0" Is False

When null is compared with a string, PHP converts null to an empty string "" and compares the two strings: "" == "0" is false. When null is compared with a bool, int, or array, both sides are converted to booleans, and since null, 0, and [] are all falsy, they compare as equal.

Rule: always use === null or !== null.


NULL in Databases and JSON

SQL NULL Becomes PHP null

When a database column contains NULL, PDO and MySQLi return PHP null for that column:

<?php
// A row as it may be returned from the database
$row = ['id' => 7, 'name' => 'Lakshmi', 'phone' => null];

$phone = $row['phone'] ?? 'Not provided';

echo "Phone: $phone";

Output

Phone: Not provided

When inserting data, binding a PHP null with a prepared statement stores SQL NULL (not the text "null" or an empty string). Prepared statements are covered in the MySQL Database section.

JSON null

<?php
$json = '{"name": "Kiran", "nickname": null}';
$data = json_decode($json, true);

var_dump($data['nickname']);
var_dump(json_encode(['nickname' => null]));

Output

NULL
string(17) "{"nickname":null}"

JSON null and PHP null map directly to each other in both directions.


Practical Example: Building a User Profile With Optional Fields

<?php
function buildProfile(array $user): string
{
    $name = $user['name'] ?? 'Guest';
    $city = $user['city'] ?? null;
    $website = $user['website'] ?? null;

    $lines = ["Name: $name"];

    if ($city !== null) {
        $lines[] = "City: $city";
    }

    if ($website !== null) {
        $lines[] = "Website: $website";
    }

    return implode("\n", $lines);
}

echo buildProfile(['name' => 'Divya', 'city' => 'Coimbatore']) . "\n\n";
echo buildProfile(['name' => 'Arun', 'website' => 'https://arun.dev']) . "\n\n";
echo buildProfile([]) . "\n";

Output

Name: Divya
City: Coimbatore

Name: Arun
Website: https://arun.dev

Name: Guest

Step-by-Step Explanation

  1. ?? 'Guest' gives the name a default when it is missing.
  2. ?? null reads optional fields safely without warnings and makes "missing" explicit as null.
  3. !== null checks decide which lines to include. An empty string would still be included, because it is a real (if empty) value; validation of empty strings would be handled separately.
  4. $lines[] = ... appends a line to the array, and implode("\n", $lines) joins the lines with line breaks.

The output only contains the information that actually exists, with no blank "City:" lines and no warnings.


Common Mistakes

Treating null, 0, and "" as the Same Thing

Effect: A real value of 0 (such as a zero discount) is replaced with a default, or missing values are stored as 0.

Fix: Use === null and ??, which only react to null.

Using isset() When Keys May Exist With null

Effect: A key explicitly set to null is reported as missing.

Fix: Use array_key_exists() when the distinction matters.

Calling Methods on Possibly-null Values

Effect: Error: Call to a member function ... on null.

Fix: Check for null first or use the nullsafe operator ?->.

Passing null to Built-in String Functions

Effect: Deprecation notices in PHP 8.1+, and future errors.

Fix: Provide a default: trim($value ?? '').

Comparing With == null

Effect: 0, "", false, and [] are all considered equal to null.

Fix: Use === null.

Using the Removed (unset) Cast

Effect: The (unset) cast, which converted values to null, was deprecated in PHP 7.2 and removed in PHP 8.0; it causes a fatal error.

Fix: Assign null directly: $value = null;.


Best Practices

  • Use null to mean "no value" and keep it distinct from 0, "", and false.
  • Check for null with === null / !== null.
  • Read optional array keys and input with ??.
  • Fill defaults with ??=.
  • Use ?-> for chains of objects where any link may be missing.
  • Declare nullable types (?string, string|null) so missing values are part of the function contract.
  • Convert null explicitly before passing it to built-in functions that expect strings or numbers.

Official reference: https://www.php.net/manual/en/language.types.null.php

0 Comments

Reviewed before they appear

No comments yet.

Data Mining
Introduction to Data Mining Data Mining Implementation Process Data Mining Architecture Data Mining Techniques KDD: Knowledge Discovery in Databases History of Data Mining Data Mining Tools Data Mining vs Machine Learning Facebook Data Mining Social Media Data Mining Methods Clustering in Data Mining Text Data Mining Bagging vs Boosting Data Mining vs Data Warehousing Social Media Data Mining Data Mining: Bayesian Classifiers Data Mining: World Wide Web Different Types of Clustering Bitcoin Mining and Blockchain Data Mining Orange Data Mining Data Mining vs Big Data Decision Tree Induction Educational Data Mining Data Mining in Healthcare Apriori Algorithm Data Integration in Data Mining Difference Between Data Mining and Text Mining Discretization in Data Mining Redundancy and Correlation in Data Mining Classification of Data Mining Systems Classification Algorithms in Data Mining Data Generalization in Data Mining Classification and Prediction in Data Mining Regression in Data Mining What Is an Outlier in Data Mining Data Cleaning in Data Mining Data Processing in Data Mining Data Mining Task Primitives Web Content Mining, Web Structure Mining, and Web Usage Mini Binning in Data Mining KDD vs. Data Mining Noise in Data Mining BIRCH in Data Mining Stemming in Data Mining Feature Transformation in Data Mining Visual and Audio Data Mining Class Comparison Methods in Data Mining Data Selection in Data Mining Tasks and Functionalities of Data Mining Ubiquitous and Invisible Data Mining Importance of Data Mining Data Quality in Data Mining Mining Frequent Patterns in Data Mining Data Warehouse and OLAP Technology for Data Mining Need for Data Mining Pattern Evaluation Methods in Data Mining Logarithms and Exponents in Complexity Analysis Time Series Clustering What is the C4.5 Algorithm and How Does It Work? Expanding Contractions in Text Mining Cosine Similarity in Data Mining Lazy Learning in Data Mining Neural Networks in Data Mining Building a Text Normalizer Shallow Parsing Data Pipeline Orchestration Big Data vs Small Data Myths of Data Mining Data Reduction in Data Mining Data Mining Models Difference Between Data Mining and Data Science Difference Between Data Mining and Statistics Difference Between Data Mining and Web Mining Difference Between Data Mining and Data Analysis Difference Between Business Intelligence and Data Mining Difference Between Data Mining and Data Visualization Data Mining vs Data Analytics Types of Data Mining Difference Between Data Profiling and Data Mining Predictive Analytics vs Data Mining Difference Between Data Mining and OLAP Descriptive and Predictive Data Mining Difference Between Spatial and Temporal Data Mining Difference Between Classification and Clustering in Data Min Hierarchical Clustering in Data Mining Density-Based Clustering in Data Mining What Is Aggregation in Data Mining?
Ask about this post
AI Ask about this post

Ask questions about PHP NULL and get answers drawn from it.

Signed-in readers only.