mardi 9 février 2021

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.

Aucun commentaire:

Enregistrer un commentaire