Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order in conditional statements [duplicate]

Tags:

php

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 }
like image 921
ken Avatar asked Jun 24 '12 22:06

ken


People also ask

Does order matter in a conditional block?

Yes, the order of the conditions matters.

DO IF statements execute in order?

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.

Does if-else follow sequential flow?

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.

Are IF statements evaluated left to right?

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.


2 Answers

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.

like image 58
nickb Avatar answered Oct 07 '22 10:10

nickb


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.

like image 34
Sean Johnson Avatar answered Oct 07 '22 11:10

Sean Johnson