Learn how to declare and convert null variables in PHP using the NULL constant and the settype() function. This tutorial covers handling null values and converting them to strings, integers, or other types for better data consistency.
You spin up a variable before you have anything to put in it yet. In PHP, that empty slot is NULL. Here’s how to declare one, how to switch its type later, and one honest catch about testing for it.
Declaring a Null Variable in PHP
It’s as plain as it looks. Assign the NULL keyword and the variable exists but holds no value. You’ll reach for this when you want to set something up now and fill it in later.
Example of Declaring a Null Variable:
// Declare a variable and set it to NULL $content = NULL;
At this point $content is defined but empty. Assign a real value to it whenever your logic is ready.
Changing the Variable Type Using settype()
PHP’s settype() function changes a variable’s type in place. So you can start with NULL and later force it to a string, integer, float, or array.
Example of Changing the Type of a Null Variable:
// Declare a variable and set it to NULL $content = NULL; // Convert the variable to a string settype( $content, 'string' );
After that call, $content is an empty string '' instead of NULL. Same idea for the other types.
One catch worth knowing
A variable set to NULL is defined, but isset( $content ) still returns false on it. That trips people up. If you actually want to check for null, use is_null( $content ) or $content === null. And if you want the variable gone entirely, that’s unset(), which is a different thing from setting it to NULL. Keep those three straight and null stops biting you.


