Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this work: if ( isset($var) && $var ){

Tags:

php

Lets say I have a variable $var that has not been defined. Why don't I get errors with this statement:

if ( isset($var) && $var ){
    // something
} else {
    // do something else
}

How can you check whether something is true or not "&& $var" if it is not set yet? Does isset() do something to the if statement. Surely this should return:

Notice: Undefined variable:$var
like image 617
ed209 Avatar asked Dec 02 '22 06:12

ed209


1 Answers

When the first part of the if statement fails, the rest of it is not evaluated, since the entire statement can not be true. Only if the isset part is true, does the execution reach your $var statement.

This is a standard language feature and is common to most programming languages.

It is called "Short Circuit Evaluation", and you can learn more about it on Wikipedia here : http://en.wikipedia.org/wiki/Short-circuit_evaluation

like image 122
Rik Heywood Avatar answered Dec 04 '22 13:12

Rik Heywood