null and empty value
Learn the null type and how it differs from an empty string and 0.
What does null mean?
null is a special type marking that a variable has no value. Example: $note = null;
null means "unknown", "not yet set" or "intentionally empty". It is not the same as an empty string "" or zero 0.
If you echo null, the output is empty because null becomes an empty string.
Use unset() to remove a variable and is_null() to test for null.
null, 0 and "" are different
These three values are often confused but they have different types in PHP:
null— no value, type NULL.0— integer zero, type integer.""— empty text, type string.
For example, a stock count of 0 means "out of stock"; null means "stock not entered".
This distinction matters in databases and forms; using the wrong type can cause data loss.
Exercise Show the null value inside brackets
Assign "Notebook" to $productName and null to $note. On the first line print Product: Notebook, on the second line print Note: []; end each line with \n.
Show example solution
"Product: " . $productName . "\n". Second echo: "Note: [" . $note . "]\n".
Example solution:
<?php
$productName = "Notebook";
$note = null;
echo "Product: " . $productName . "\n";
echo "Note: [" . $note . "]\n";
Test yourself
-
What is the difference between $a = null; and $b = "";?
$a = null; $b = "";- They mean the same thing.
- $a is a number, $b is text.
- Both are treated as numbers.
- $a has type NULL, $b is an empty string.
Show answer
$a has type NULL, $b is an empty string. — Correct! null is a type, while "" is an empty string value.
-
Assign null to $note
$note = ____;Show answer
$note = null; -
Which assignment makes the variable null?
- $note = null;
- $note = "null";
- $note = 0;
- $note = "";
Show answer
$note = null; — Correct! The unquoted null is a NULL-typed value.