Assignments inside an "if" condition in PHP
Author | Message |
---|---|
Jojo | # Posted yesterday |
Hi everyone, I'm trying to optimize my code as much as possible, and I was wondering if something like this is doable: if (a = b or c = d) Knowing that I tried using | |
Ads | |
Clara | # Posted yesterday |
![]() |
Hello, Optimizing doesn't mean squeezing your code into as few lines as possible. It means improving performance. Writing convoluted one-liners makes your code harder to maintain down the road, both for you and for any teammates trying to figure out what it does. |
Rel0ad | # Posted two hours ago |
![]() |
"Factorizing" would probably be a better term here. Incidentally, why didn't you try or? |
Phoenix | # Posted two hours ago |
![]() |
For once I have to agree with Clara, this isn't going to optimize your code in any way. That said, getting a solid grasp on operator precedence is definitely worthwhile (it's even in the tutorial). Here's the precedence order for the operators you’re dealing with (from highest to lowest): And don't forget their associativity:
So: $a = $b || $c = $d is evaluated as: $a = ($b || ($c = $d)) Whereas: $a = $b or $c = $d is interpreted as: ($a = $b) or ($c = $d) Doing assignments inside an if is actually pretty common. For ex: if (false !== $handle = fopen('file.txt', 'r')) That's a well-known idiom. Same goes for having multiple operators in an expression. Just don't go full-on Code Golf. That said, practicing this kind of thing in a sandbox is a great way to get comfortable with operator precedence. |
Jojo | # Posted one hour ago |
Thanks for the info. In the end, I guess I couldn't really get what I originally wanted without asking lol. Maybe I should've posted the original version of the code as I've FAFO with it since then. |
|
Gandalf | # Posted one hour ago |
![]() |
In the same vein... $b = false; You can pretty easily guess where this code would fail. |
Jojo | # Posted 7 minutes ago |
LOL! Nice catch ^^ |
Post a reply
Please be kind and courteous in your replies. Don't roast others for no reason.