user1355300
user1355300

Reputation: 4987

PHP Checking input with isset

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']!="") ) {
    ..
}

Upvotes: 0

Views: 1129

Answers (5)

Salman Arshad
Salman Arshad

Reputation: 272106

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.

Upvotes: 1

user1299518
user1299518

Reputation:

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...

Upvotes: 1

Rawkode
Rawkode

Reputation: 22592

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.

Upvotes: 1

Antonio Ciccia
Antonio Ciccia

Reputation: 736

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

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

Upvotes: 1

acme
acme

Reputation: 14856

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...).

Upvotes: 2

Related Questions