Is there a difference between these two statements:
if ($a == 'hello') { ... }
and
if ('hello' == $a) { ... }
I've noticed applications like Wordpress tend to use the latter, whereas I usually use the former.
I seem to remember reading something a while ago giving justification for the latter, but I can't recall the reasoning behind it.
If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.
Yes, you can assign the value of variable inside if.
The IF statement evaluates the given conditional expression. If the result is true (i.e. nonzero), then the statements following the <IF> tag are executed. If the result is false, those statements are skipped and control falls to the next statement after the closing </IF> tag.
The & means "Don't take the variable, take the place in memory where this variable is stored." It's a little complicated, but it's necessary so that C can change the value of the variable.
There is no difference. It is used so that an error is thrown in case you accidentally make an assignment instead of a comparison:
if('hello' = $a)
if($a = 'hello')
would assign to the variable and not throw an error.
It might also be used to explicitly show that if you have an assignment in an if
statement, you really want to have it there and it is not a mistake (consistency).
The justifikation for the latter is that if you mistakenly type =
instead of ==
(assignment instead of comparision) you'll get compiler error (can't assign to constant).
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