• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

quick question about conditionals in PHP

bitt3n

Senior member
instead of evaluating whether a variable is set, and then evaluating its contents, like this

if (isset($var)) {
if ($var == 3) {
echo($var);
}
}

is it considered bad form to do this

if ( (isset($var)) && ($var==3) ) {
echo($var);
}

since it's obvious what's going on and this should never fail (since PHP stops evaluating the conditional if isset() returns false?
 
Short-circuit evaluation is wonderful. I do the latter all the time; then again, I only have a year of paid PHP development under my belt.
 
Originally posted by: bitt3n
instead of evaluating whether a variable is set, and then evaluating its contents, like this

if (isset($var)) {
if ($var == 3) {
echo($var);
}
}

is it considered bad form to do this

if ( (isset($var)) && ($var==3) ) {
echo($var);
}

since it's obvious what's going on and this should never fail (since PHP stops evaluating the conditional if isset() returns false?

If the first condition is false, the second will not be evaluated. Plus the second code snippet is more readable. I always try to cut down on nested ifs as much as possible.
 
I'd go as far to say that the first one would be used by a less experienced developer

second form is short and sweet. I like it
 
the 2nd one if thats all thats happening

normally there's an isset conditional, and inside there's a bunch of other value based conditionals or a switch statement
 
Originally posted by: presidentender
Originally posted by: txrandom
or just do:

if ($var == 3) {
echo $var;
}

That squawks if $var isn't set.

not it doesnt.

of $var isnt set its assigned NULL so it just doesnt evaluate to 3.

so actually you can cut out the braces entirely and it would work as intended

if($var==3) echo $var;

DONE.
 
I try to cut down on nested "if" statements whenever possible and make use of short-circuit evaluation, unless the expression in the "if" statement gets to be a little complex/long-winded.
 
Originally posted by: txrandom
Originally posted by: presidentender
Originally posted by: txrandom
or just do:

if ($var == 3) {
echo $var;
}

That squawks if $var isn't set.

I'm not getting any errors when I do it. I got display errors set to on.

Alright, I know what I'm doing wrong. When using stuff from inside an array (for me, this is usually $_GET) it'll throw an "undefined offset" error, so I need to use the isset() for that. $var==3 is fine if $var isn't set. I was wrong.

(of course, maybe I still am)
 
Back
Top