isset question

Started by 127.0.0.1, November 27, 2003, 03:32:00 PM

Previous topic - Next topic

127.0.0.1

What is the difference between writing:

if (isset ($variable)) { blah blah blah; }

and

if ($variable) { blah blah blah; }

They both check to see if the variable has been set correct?

Also, I was wondering what is the difference between the & and ; when getting variables through the url? Many php scripts use & while smf/yabbse use ;

Thanks

Chris Cromer

#1
The difference is that isset checks to see if the variable exists. The other one only checks if it is set to be true. If you used the second one and error would occur if the variable didn't exist, because it is only designed to see if the variable is set to true or false, but if the variable doesn't exist it can't check so it gives a notice. Isset won't return an error because it's is designed to see if it exists or not, not to check whether it is set to something.

And there is no difference between the ; and the &. & is the default for all servers ; is not done by the server but by SMF/YaBBSE itself, so using ; will not work in your scripts that you make(without special code), so use &.
Chris Cromer

"I was here, here I was, was I here, sure I was" - The little voice in my head.

[Unknown]

Here's an example to illustrate Chris Cromer's point:

<?php
$var 
false;

if (isset(
$var))
  echo 
'$var is set!';

if (
$var)
  echo 
'$var evaluates to true!';

?>


As it happens, the second one will NOT be outputted.  Because if (false) isn't going to happen.

Further, if you have error reporting enabled, you'll get a notice telling you that you tried to use an undefined variable.  Even more, it will slow your script down whatever error reporting is set to.

-[Unknown]

127.0.0.1

Ah, I understand. The second if statement only checks the boolean value. Thanks guys. :)

Anguz

you could use empty() for that and cover both situations

from the manual http://mx.php.net/manual/en/function.empty.php
Quoteempty() returns FALSE if var has a non-empty or non-zero value. In otherwords, "", 0, "0", NULL, FALSE, array(), var $var;, and objects with empty properties, are all considered empty. TRUE is returned if var is empty.

empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.

so your line would be better as

<?php
if(!empty($var)) {blah blah blah;}
?>
Cristián Lávaque http://cristianlavaque.com

Advertisement: