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?
== is an equality comparison operator, it is used to compare two values. So in your if statement you are asking JavaScript to see if divList. style. display is equal to "None" .
The === operator means "is exactly equal to," matching by both value and data type. The == operator means "is equal to," matching by value only.
You will also see a single equal sign being used to denote variables and the like. Just keep it all straight by remembering that only the double equal sign means “is equal to” and the single equal sign can be roughly translated into “is.”
Single = is an assignment operator and will always equate to true in an if statement (assuming it is a non negative value). Double = ,as in == , is a comparison and will equate to true only if the values on either side of the operator are equal. Follow this answer to receive notifications.
Testing the result of a function that returns an error:
if (($err = some_function())) {
echo "Error: " . $err;
}
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:
if($a)
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()
One of the most common usecases is to make sure something exists (or is truthy), and then use it inside the block, for example:
while ($row = $dbConnection->fetch()) { //Make sure that $dbConnection->fetch() is not false or NULL...
//You can use $row here!
}
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