Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if (variable)

Tags:

php

In various PHP tutorials I see this syntax -

if ($_POST) {
  do something
}

I want to know whether this is equivalent to either isset or !(empty) (either one) or has different properties.

like image 879
Joel Blum Avatar asked Nov 28 '12 07:11

Joel Blum


1 Answers

It attempts to evaluate the expression and cast it to boolean.

See 'Converting to boolean' at http://php.net/manual/en/language.types.boolean.php to see which values will be equivalent to true and which to false.

It does NOT however check for array key existence (i.e. isset), so if you try if ($_GET['somekey']) but somekey does not exist, you will see PHP Notice: Undefined index: somekey and then false will be assumed.

The best practice would be to perform empty() or isset() checks manually first as fits.

like image 167
mkilmanas Avatar answered Sep 24 '22 02:09

mkilmanas