PHP how to check variable if not empty

Posted on Aug 18, 2022

Learn how to check the value of your PHP variable if it's not empty

Photo from Unsplash

To check if your PHP variable is not empty, you can negate the empty() function using the bang operator (!).

The PHP empty() function is used to check whether a variable is empty or NULL.

A variable is considered empty when it has not been declared or defined with an empty string:

// 👇 this is an empty string
$name = ""; 

Here are some examples of if not empty check using PHP:

<?php
$name = "Nathan";

// 👇 if name is not empty, echo some text
if (!empty($name)) {
    echo "NAME is not empty";
}

// 👇 if age is not empty, echo some text
if (!empty($age)) {
    echo "AGE is not empty";
}

To check if a PHP variable is not empty, you can call the negated empty function or !empty() in your if statement.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.