Possible Duplicate:
php false place in condition
I have noticed that a lot of PHP code uses conditional statements like CONST == VARIABLE. I grew up with the syntax always articulated in reverse. Is there a reason for this structure?
Example:
// this is the way I see it most typically represented in PHP
if ( false == $foobar ) { // do this }
// this is the way I normally do it
if ( $foobar == false ) { // do this }
Yes, the order of the conditions matters.
The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.
The if and else clauses each only embed a single statement as option, so the last statement is not part of the if-else statement. Instead it is a part of the normal sequential flow of statements. It is always executed after the if-else statement, no matter what happens inside the if-else statement.
You can combine two or more conditional expressions on the IF statement. ISPF evaluates the conditional expressions on the IF statement from left to right, starting with the first expression and proceeding to the next and subsequent expressions on the IF statement until processing is complete.
This is to prevent a common typo between ==
and =
, known as a yoda condition. Consider the following:
if( false = $foobar) {
This would result in an error, catching what would be considered a bug, since you cannot assign anything to false
. On the contrary:
if( $foobar = false) {
This is valid syntax, and is quite an easy mistake to make.
However, I typically prefer the if( $foobar == false)
syntax, as unit tests should be able to catch these programmatic mistakes.
The way you normally do it is exactly how most programmers do it. The first example is called a yoda condition:
http://www.dodgycoder.net/2011/11/yoda-conditions-pokemon-exception.html
and is not the norm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With