Recently, i opened some WordPress files. It uses "if" like this if ('john' == $name) { } else if ('doe' == $name) { } PHP: My question is which is better, the WP style, or the normal style : if ($name == 'john') { } else if ($name == 'doe') { } PHP: There must be a reason so that most WP files use their own "if" style Any opinion is appreciated
It really doesn't matter. Both will work as well. However, my preference goes to the second way, where the comparison is more logical.
Thanks for the quick response. I am curious too, whether the wp style is faster in execution time or something like that (i have not tested the execution time btw)
The best way is whats best for you, as it will be you who will have to potentially bugfix and troubleshoot the code
Hello, Main thing is which is more Effectively. As per my knowledge 2nd option is more suitable then 1st.
you mean which is faster? in real world terms I dont think it matters as you will probably shave 0.0001 ms off script execution time. its not even worth worrying about. I can see no idea why WP does it differnetly, probably just a historical thing.
The reason they probably do it is that there is a school of thought that says when making comparisons against a constant, use the constant first. This is to help pick up when they miss an equal sign and make it an assignment, not a comparison. In this case, with the constant first, you will get an error. eg. Code is meant to be: if ( $name == 'John ) { but is accidentally typed as: if ( $name = 'John' ) { this is valid code and accepted by the parser, even though it doesn't do what it was expected to do. On the other hand, if they wanted to type: if ( 'John' == $name ) { but typed; if ( 'John' = $name ) { it would fail, as you can't assign a different value to 'John'. It's just one of many ways to help pick up subtle coding mistakes.
It makes absolutely no difference at all ... variables are usually first in conditions, but either way is correct ...