-1

I'm upgrading an old code from PHP 4 to PHP 5 and what I often see is:

if (!$variable) {
    // for example...
    $variable = "test";
}

To understand the code I need to know if it was possible earlier in PHP 4 times to check the existence of a variable by doing so.

I'm sorry but I couldn't google the answer to that.

Cutaraca
  • 2,069
  • 3
  • 14
  • 21

1 Answers1

0

if (!$variable) tests if $variable evaluates to false. According to the chapter Converting to boolean, a lot of things evaluate to false:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Therefore, using this kind of code to test if a variable is already set is dangerous. Also, it will generate notices when the variable is used but not set.

Yes, the code will execute with PHP 4. But you may get unexpected results when $variable is set to 0, the empty string or the string '0'.

For cleaner code, you should use isset:

if (!isset($variable)) {
    // for example...
    $variable = "test";
}

According to the documentation, isset was introduced with PHP 4.

Jocelyn
  • 11,209
  • 10
  • 43
  • 60
  • I know there is isset and that you should use that if you're trying to check a variable existence. But that was not my question. – Cutaraca Apr 30 '17 at 12:53
  • thank you! i should have just try it out myself on http://sandbox.onlinephpfunctions.com/ – Cutaraca Apr 30 '17 at 13:16