John Higgins
John Higgins

Reputation: 907

Detecting if a variable is empty

I have a variable of $message that when I echo displays nothing. Unfortunately the following code does not work.

if (!$message) {
    echo 'Nothing here!';
}

When I var_dump($message); I get the following:

string(48) ""

So it looks like somethings in there. Any ides?

Thanks,

John

Upvotes: 1

Views: 90

Answers (7)

Jordi Vicens
Jordi Vicens

Reputation: 772

You can use:

<?php
    is_null($var) //returns true if it's null

    empty($var) //returns true if it's empty

    isset($var) //returns true if it's not null.
?>

https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/

I hope I've helped!

Upvotes: 0

John Higgins
John Higgins

Reputation: 907

Ok - I worked it out. I was building the $message variable with a load of MySQL queries and if there we're results displaying the in a table. I had a few tags outside of a if (mysqli_num_rows($result) <> 0) { } clause so they we're being saved in the variable.

Thanks all for your help anyway.

Upvotes: 0

Marek Bern&#225;d
Marek Bern&#225;d

Reputation: 629

When you are typing the name of your question, notice, that below many same questions could appear, like in this post, and you will not duplicate it then. For example, first post where you can find many answers: check if variable empty

And you save your time for typing question ;-)

Upvotes: 0

Gerard
Gerard

Reputation: 66

Use empty()

isset() will return true for empty value

What's the difference between 'isset()' and '!empty()' in PHP?

Upvotes: 1

Adrien QUINT
Adrien QUINT

Reputation: 43

You could also use :

if($var == "")
{
    echo("nothing here");
}

Upvotes: 1

Mark Knol
Mark Knol

Reputation: 10163

Try this:

if(!$message || $message == "") {
   echo 'Nothing here!';
}

You can also use isset($message) or empty($message).

Upvotes: 0

clearshot66
clearshot66

Reputation: 2302

use one of these:

http://php.net/manual/en/function.empty.php

if(isset($message)){
   echo "variable has value set";
}

if(!empty($message)){ 
   echo "Variable is empty";
}

Upvotes: 0

Related Questions