O Connor
O Connor

Reputation: 4392

PHP check if a variable is empty or not

In my case, the variables $nr and $str can have only two possible values. $nr can contain integer/numeric or null, not "null" between double quotes. $str can contain a string value or null. Can I just check if the variables are empty or not like this?

if ($nr) {}
if (! $nr) { return; }
if ($str) {}
if (! $str) { return; }

I think the answer is Yes but some code snippets of others made me doubt about that because they check it as following.

if (empty($var) || "" === $var || null === $var) { return; }}

I think this is unnecessary. To be specific, it is in PHP7.4.

Upvotes: 0

Views: 1002

Answers (2)

deceze
deceze

Reputation: 522081

if ($var)/if (!$var) simply check for truthy/falsey values respectively (they're complimentary opposites, which one you choose is merely a question of which makes more sense in your flow). Falsey values in PHP are:

  • false
  • null
  • 0, -0, 0.0, -0.0
  • "0" (0 as a string)
  • "" (empty string)
  • array() (empty array)
  • empty SimpleXML objects (interesting special case; thanks Obama! 🤔)

Everything else is truthy.

So, if none of your desired values fall into this list and all of your undesired values are in this list, then a simple if ($var)/if (!$var) will do just fine. If your desired/undesired list does not happen to align with this and you want some of column A but also some of column B, then you need to do more specific and complicated checks.

The only time you'll want to use emtpy is if the variable you're checking may legitimately not exist. empty($var) is just !$var, but doesn't raise an error if $var doesn't exist at all. That's its only purpose, and you do not want to suppress error reporting unless you have to. In a properly written program where you declare your variables properly, there should be very very little use for empty, since you should know what variables exist and which don't.

Upvotes: 1

Tschallacka
Tschallacka

Reputation: 28722

You can check https://www.php.net/manual/en/types.comparisons.php to see what can be used to check if something is truthy or falsy. Below is the table of the link before condensed into a table of things you can plug into an if statement and what the results will be.

Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an int. false is a bool while "false" is a string.

Expression bool : if($x)
$x = ""; false
$x = null; false
var $x; false
$x is undefined false
$x = array(); false
$x = array('a', 'b'); true
$x = false; false
$x = true; true
$x = 1; true
$x = 42; true
$x = 0; false
$x = -1; true
$x = "1"; true
$x = "0"; false
$x = "-1"; true
$x = "php"; true
$x = "true"; true
$x = "false"; true

Upvotes: 3

Related Questions