Jump to content

set variable and compare in one command


NotionCommotion

Recommended Posts

I typically only use the first two solutions.  Is there anything wrong with the third?  Is there any more streamlined way to do it?

function f1($x){return $x*1;}
function f2($x){return $x*1;}

$x=2;$y=1;

if(f1($x)>f2($y)){echo(f2($y)."\n");}

// or

$f2_y=f2($y);
if(f1($x)>$f2_y){echo($f2_y."\n");}

// or

if(f1($x)>$f2_y=f2($y)){echo($f2_y."\n");}
Link to comment
https://forums.phpfreaks.com/topic/293773-set-variable-and-compare-in-one-command/
Share on other sites

Thanks phpaddiction, and welcome to php freaks.

 

Do you know whether the parenthesis around setting $f2_y are absolutely required.  I looked at http://php.net/manual/en/language.operators.precedence.php, and wasn't sure whether = had higher precedence than >.  Regardless, I feel they make the code more readable.

You could always try it and see.

 

I had done so before starting this post.  As far as I could tell, the equal sign has higher precedence than the > sign, and the parenthesis are not required.  Just couldn't find this documented anywhere.

I had done so before starting this post.  As far as I could tell, the equal sign has higher precedence than the > sign, and the parenthesis are not required.  Just couldn't find this documented anywhere.

Actually it has lower precedence.. Since the = comes after the > in the example, it works without the extra parenthesis.

 

This on the other hand: if($f1_x=f1($x) > f2($y)){ would be interpreted as $f1_x = (f1($x) > f2($y)) and $f1_x would be a boolean true/false not the return value of the function.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.