Null Variables

A Null variable is a variable that doesn’t have a value. A variable is considered Null in following scenarios:

When you have created a variable but you haven’t assigned a value to it, then that variable is considered a Null variable.

When creating a variable in PHP, you don’t always need to assign a value to it. You can just define the variable without a value by skipping its assignment part as shown in the below example:

<?php
$username;

In the above example, we have defined a variable called $username. We have intentionally skipped the assignment part so it makes $username a Null variable.

When you use PHP function unset() to destroy a variable, that will also make that variable Null.

When you do something like below:

<?php
unset($variable);

it will destroy that variable. That means, after unsetting a variable you won’t be able to access it’s value later. unset() makes it null. Check out the below example to see this in action:

# step 1: set a variable
$person = 'Bill Gates';

# step 2: show $person
echo "Person's name is $person";

# add some space below
echo "<br><br>";

# step 3: unset $person
unset($person);

# step 4: show the $person again
echo "Person's name is $person";

When you run the above code, you should see something similar to following:

Person's name is Bill Gates

Person's name is

In the first step we have created a variable called $person and assigned the value ‘Bill Gates’. Second step uses $person variable to construct a message that displayed as ‘Person’s name is Bill Gates’. So far so good. Next in the third step we have used PHP’s unset() function to destroy the variable. Finally we again construct the message as we did in the step 2. But this time you will see ‘Bill Gates’ is missing from the output. That’s because unset() has made $person a null variable. So it doesn’t have a value.

When you explicitly assign NULL as the value of some variable, that variable is indeed becomes a null variable

See below example:

# step 1: set a variable
$person = 'Bill Gates';

# step 2: show $person
echo "Person's name is $person";

# add some space below
echo "<br><br>";

# step 3: set $person to NULL
$person = NULL;

# step 4: show the $person again
echo "Person's name is $person";

we have taken the same code sample that we used in the above unset() example. Only the 3rd step has changed. Instead of unset() this time we have re-assigned $person’s value to NULL. When you run this, the result will be exactly similar to what you saw in the previous scenario where you unset() the variable. The variable has become null.

Comments

So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar



Do NOT follow this link or you will be banned from the site!