PHP Variables – Check if a variable is null

In this post we will be creating PHP script that will check if an existing variable is null, to do this we will be using the ‘is_null()’ PHP function. For this example our variables will be stored in an array and we will carry out a check on each item within.

See our array of items for this example below.

$array = array(26.132, "10.243", null, "Aloha", "", 192, null);

In the snippet of PHP code below we are iterating the above array of variables and using the ‘is_null()’ function to carry out our checks. The True or False values will be printed beside the item and each item will be printed on a new line.

<?php
$array = array(26.132, "10.243", null, "Aloha", "", 192, null);

foreach ($array as $item) {
    echo $item . " - " ;
    echo var_dump(is_null($item)) . "<br>";
}

?>

The above would return the following as output.

26.132 - bool(false)
10.243 - bool(false)
- bool(true)
Aloha - bool(false)
- bool(false)
192 - bool(false)
- bool(true)

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply