Using one equals sign in an if statement

php

Solution

PHP, like also C, allows to write any expression into an if-condition.

This can be an expression like:

if(!$db=new database()) die("NO DATABASE CONNECTION");

But it has rather the background that the expression `$a="abc"` is evaluated a different way:

- Set the value of $a to abc

- Rest of the expression is: `if($a)`

- $a is != 0, so it is true MOST IMPORTANT

- Expression is true, go into if-case

So the expression is evaluated to if(true) because the priority table of operators make the expression succeed. It is not a mistake of PHP, it is rather the definition of TRUE/FALSE and how things get evaluated.

This can also be used in loops like shown in another answer for the loop expression with `$db->fetch()`

Problem

In a PHP `if` statement, when I am comparing a variable I would need to use two `==` signs. For example, ``` if($foo == 'bar'){ //Run code } ``` But if I were to use one equals sign like this: ``` if($foo = 'bar'){ //Run code } ``` This would actually set the `$foo` variable. Why would you ever need to set a variable like this inside an `if` statement? I can't think of one instance where this would be useful, and many programmers I've spoken to feel the same way. Is there a reason why PHP allows you to set a variable this way?

Original source