Jeffrey Simon
Jeffrey Simon

Reputation: 1034

Simplified test for non-empty variable

I am maintaining some old PHP code and I find many places in the code a test for a variable being non-empty of the following form:

if (!(isset($field_name) && strlen($field_name) > 0))

To my way of thinking, the following much simpler form would do exactly the same thing:

if ($field_name)

Am I missing some subltety whereby the more complex form is more precise? I have tended to use the simpler form any place where I need to add new code.

Upvotes: 0

Views: 60

Answers (4)

zx81
zx81

Reputation: 41838

You are right that the code you found is odd. It should probably be either:

if(!(isset($field_name)) { ... do something }

or

if(isset($field_name) && strlen($field_name) > 0 )  { ... do something }

...As you can appreciate, there is no need to test the length of a variable that is not defined.

However, if($field_name) is not the same as if(!(isset($field_name)), and the difference is not subtle. Indeed, the former will earn you a Undefined variable: fieldname if by some stroke of bad luck $field_name is not defined.

What's the difference?

  1. if($field_name) tests if the existing variable $field_name evaluates to TRUE. For instance, it's value might be "my dog", and that evaluates to TRUE
  2. if(!(isset($field_name)) tests if the variable $field_name exists at all.

Upvotes: 0

John Conde
John Conde

Reputation: 219804

They do not do the same thing. The first code sample:

  1. Checks if $field_name exists (I figure the ! is unintentional as it doesn't make sense the way it is written)
  2. Checks if $field_name has a string length greater than zero

The second code sample:

  1. Checks if the variable has a Boolean true value
  2. Will throw an error if $field_name is not set.

The first snippet is clear and precise in its intent and performs a specific task.

The second snippet is very basic and only verifies the variable has a Boolean true value (and there are better ways to do that). If $field_name contains a string "0" this snippet will cause a hard to spot bug as it will fail as "0" evaluates to false. The first snippet would catch this.

Upvotes: 0

jeroen
jeroen

Reputation: 91734

You can use empty() to replace your first line:

if (!empty($field_name))

The problem with your second example is that it will generate a warning if the variable is not set. Both empty() and isset() will not generate a warning for non-existing variables.

Note that you always have to account for possible values so if your value can be 0 or '0', this will not work as after $var = 0;, empty($var) will evaluate to true.

Upvotes: 1

Sesertin
Sesertin

Reputation: 462

if ($field) will fail if $field is null, 0, 0.00, false or anything that can be casted false

if(!isset($field))

will fail if $field has not been declared at all

Upvotes: 0

Related Questions