Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is isset($foo) functionally identical to !$foo?

Tags:

php

Will isset($foo) always display the same result as !$foo?

I have a peice of code where I'm getting php warnings for using:

if(!$foo){}

And I'm pretty sure that I should be using:

if(!isset($foo)){}

And that made me curious whether I'm changing the functionality here or not.

like image 758
Citizen Avatar asked Dec 01 '22 19:12

Citizen


2 Answers

No.

Using a boolean negation operator ! a variable is casted to boolean. Boolean FALSE is equal to NULL (this is functionally however the same as isset()), empty string, 0, empty array.

Using isset no error is given if the variable does not exist. If you use ! with non-existent variable, E_NOTICE is shown.

like image 147
Voitcus Avatar answered Dec 25 '22 20:12

Voitcus


No.

One tests if a value is not set, the other tests if it is not true.

Compare:

<?php
$foo = 0;

if(!$foo){ echo 1; }
if(!isset($foo)){ echo 2; }
?>
like image 29
Quentin Avatar answered Dec 25 '22 20:12

Quentin