Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange variable assignment

I was studying some code I found on the web recently, and came across this php syntax:

<?php $framecharset && $frame['charset'] = $framecharset; ?>

Can someone explain what is going on in this line of code? What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?

Thanks! Pat

like image 484
cube Avatar asked Sep 04 '10 03:09

cube


1 Answers

Ah, I just wrote a blog post about this idiom in javascript:

http://www.mcphersonindustries.com/

Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.

The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).

Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.

like image 173
Alex Mcp Avatar answered Sep 22 '22 06:09

Alex Mcp