SITERAW

Assignments inside an "if" condition in PHP

Author Message
Jojo # Posted yesterday
Jojo

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 b and d are booleans and will determine whether the rest of the code executes. I want both a and c to be assigned no matter what.

I tried using ||, but it didn't work — I haven't tried using a plain or. If there's a specific way to write this, I'd love to hear it.

Ads
Clara # Posted yesterday
Clara

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
Rel0ad

"Factorizing" would probably be a better term here. Incidentally, why didn't you try or?

Phoenix # Posted two hours ago
Phoenix

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): || > = > or

And don't forget their associativity:

  • || and or are left-associative
  • = is right-associative

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
Jojo

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
Gandalf

In the same vein...

$b = false;
$d = false;

if ($a = $b && $c = $d) echo 'ok';

var_dump($a, $b, $c, $d);

You can pretty easily guess where this code would fail.

Jojo # Posted 7 minutes ago
Jojo

LOL! Nice catch ^^

Post a reply

Please be kind and courteous in your replies. Don't roast others for no reason.