Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

evaluating expressions in if statements

Status
Not open for further replies.

enigma174

IS-IT--Management
Jun 26, 2002
59
NZ
Hi,

I'm trying to better understand the if statement.
I know that you can set variabes in an if statement, eg if ($foo = bar()), then do something with $foo. But how does this work in relation to compound if statements.
Take the code below for example:

Code:
<?php

function f1 () {
  return "foo";
}

function f2 ($foo) {
  return $foo . "bar";
}

if ($a = f1() && $b = f2($a)) {
  echo "$a ... $b<br />\n";
}

?>

This returns:

1 ... bar

So it seams that the value assigned to $a is not available to the f2() function, and becomes simply "1" (True?) after the if statement is finished.
I was wondering if there's a way of making something like this work without using nested if statements?

thanks
--chris
 
It's a side effect (of an assignment) issue. Never use side effect ops in one expression. The (most of) language(s) declare undefined behaviour in that case, i.e. you may have old or new values after assignment in the (rest of) expression. You must use nested ifs in that case (or better don't use assignments, incr/decr in complex condition expressions).

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top