Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between those PHP if expressions?

What's the difference between those PHP if expressions!?

if ($var !== false)
{
    // Do something!
}


if (false !== $var)
{
    // Do something!
}

Some frameworks like Zend Framework uses the latest form while the traditional is the first.

Thanks in advance

like image 482
Omranic Avatar asked Apr 21 '10 13:04

Omranic


People also ask

What are the 4 PHP conditional statements?

if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false. if...elseif...else statement - executes different codes for more than two conditions. switch statement - selects one of many blocks of code to be ...

What are the expressions in PHP?

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

What is difference between statement and expression in PHP?

In programming language terminology, an “expression” is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything.

What is the difference between == and === comparison operators in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.


2 Answers

The result of the expression is the same however it's a good way of protecting yourself from assigning instead of comparing (e.g writing if ($var = false) instead of if ($var == false), since you can't assign the value $var to the false keyword)

like image 89
matei Avatar answered Oct 23 '22 17:10

matei


It's just a preference really. You can put it either way, a == b or b == a, but it's easier to make a mistake if you do

if ($var == false)

because if you accidentally type it with one = letter, the condition will always equal to true (because $var will be set successfully), but in case of

if (false == $var)

if you now put in =, you will get an error.

like image 38
Tower Avatar answered Oct 23 '22 16:10

Tower