Ponting
Ponting

Reputation: 2246

How to check whether variable is null or not in PHP

In PHP,

I am using One Variable called $token.

I want to check whether it's value is null or not.I have tried by checking empty/isset/is_null in if condition.But It didn't work.

when I print its value using error_log($token) then it gives output like : "(null)".

Because in database its value is "(null)".

How can I check in php whether it is (null) or not.

Please guide me on this.

Upvotes: 0

Views: 376

Answers (4)

Ponting
Ponting

Reputation: 2246

I solved my problem using strlen() condition.Thank you all for your suggestions.

Upvotes: 0

Source
Source

Reputation: 1011

or the shortest way

if($token) echo 'not null';

Upvotes: 0

Praburam S
Praburam S

Reputation: 165

What you did is also right. Even You can have some more options try following conditions

1. if($token === null){....}
2. if($token == null){....}
3. if($token == ""){....}
  1. init some a string variable

    $tmp_string = ""; $tmp_string .= $token if($tmp_string== ""){....}

Try All above. All The Best....

Upvotes: 0

raina77ow
raina77ow

Reputation: 106385

It looks like you're working not with a real null, but with a string - that's literally '(null)'. So check for that instead, with...

if ($token === '(null)') { ... }

What's more important, however, is why this value appeared in the DB in first place. Unless there's a very specific (and valid) reason to do this, you'd better store nulls (absence of information) as plain NULL value, to avoid confusion such in this case both on application and database layer.

Upvotes: 6

Related Questions