0

In order to check if an input field is empty or has any value, will the following both methods work in same way? Or is any of them better than other?

if ($options['url']) {
    ..
}

Or

if ( isset ($options['url']) &&  ($options['url']!="") ) {
    ..
}
user1355300
  • 4,867
  • 18
  • 47
  • 71

5 Answers5

2

Without checking with isset() you will get at least a notice message if $options is not an array or the index url does not exist. So isset() should be used.

You could also use

if (! empty($options['url'])) {
    ...
}

Empty() checks for any false value (like an empty string, undefined, etc...).

acme
  • 14,654
  • 7
  • 75
  • 109
1

Isset determine if a variable is not NULL and is set.

($options['url']) determine if a variable return true

Antonio Ciccia
  • 726
  • 3
  • 8
  • 18
1

The code below only checks that the value, assuming the key exists, is true. A notice will be fired if the key doesn't exist. if ($options['url']) { .. }

isset will tell you if the key exists and the value is not null.

I'd use empty as it will return false if the key doesn't exist and it will also return false if the key does exist yet the value is empty.

Rawkode
  • 21,990
  • 5
  • 38
  • 45
1

No.

The $options['url']!=""checks if variable is empty,

while isset($options['url']) checks if the variable has been set or is not NULL.

Anyway, calling isset() always on variables or array keys that may or may not exist must be a rule.

or you'll get all those 'undefined' warnings...

1

The following should be sufficient:

if (isset($options["url"]) && $options["url"]) {
   // ...
}
  1. The isset() is used to check if a specific key is present in the array (and to avoid the undefined index notice). It is a good programming practice. You can also use the array_key_exist() function in this case but isset is usually faster.

  2. When an expression such as $options['url'] is used inside a boolean context; its truthiness is checked (see the converting to boolean section). The empty() function produces identical result for most expressions.

Salman A
  • 262,204
  • 82
  • 430
  • 521