FtDRbwLXw6
FtDRbwLXw6

Reputation: 28929

PHP: NULLish value checking

When checking a superglobal like $_GET or $_POST for existence of a value for a particular key, is there a method that encompasses the following functionality in a more concise way?

if (isset($_POST['foo']) && $_POST['foo'] !== '') {
    // ...
}

The isset() function by itself returns TRUE even when the value is an empty string '', so I can't use that.

Using just $_POST['foo'] !== '' will work correctly by itself, but it emits an E_NOTICE for undefined index, which is undesirable.

The empty() function returns TRUE for the value "0", which is a valid value, so I can't use that, either.

Am I missing something obvious, or is this really the best/only way to do it?

Upvotes: 2

Views: 492

Answers (3)

Ed Heal
Ed Heal

Reputation: 60047

Why not do the whole post in one shot using array_merge at the start of the script.

i.e.

$default = array('foo' => "2", 'bar' => 'Hello World');
$postValues = array_merge($default, $POST);

Then use $postValues. It gets over isset everywhere in the rest of the code as the defaults will be used instead.

Upvotes: 1

Andrew Moore
Andrew Moore

Reputation: 95484

You can always silence the E_NOTICE. In this case, you expect a E_NOTICE to be thrown if the variable isn't set (and really, it's the only possible error condition here) so it is safe to be silenced.

if(@$_POST['foo'] != '') {

}

Upvotes: 2

Tadeck
Tadeck

Reputation: 137450

Probably you are looking for array_key_exists():

if (array_key_exists('foo', $_POST)){
    // will execute when $_POST['foo'] is set, even if to null, false, '' etc.
};

If you do not want to match empty string (''), then your solution is probably enough. Solution above gives you false only when the key does not exist.

Upvotes: 5

Related Questions