5

The following two ifs produced different results(first if echos hi, second does not), why? why didn't the variable assignment on $t work? is this due to $t's local scope inside the if conditional?

if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"]) && !empty($t)){
   echo 'hi'
}

if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
   if(!empty($t))echo 'hi'
}
deceze
  • 510,633
  • 85
  • 743
  • 889
user678070
  • 1,415
  • 3
  • 18
  • 28
  • [duplicate](http://stackoverflow.com/questions/5091986/unexpected-cast-to-boolean/5092026#5092026)? – meze Mar 29 '11 at 02:15

2 Answers2

13

&& has a higher precedence than =, hence the first expression is evaluated as:

isset($_REQUEST['test']) && $t = (trim($_REQUEST['test']) && !empty($t))

Since !empty($t) is evaluated before anything is assigned to $t, the expression is false. You could fix this by explicitly setting parentheses, or by using a less awkward way to write it:

if (isset($_REQUEST['test']) && trim($_REQUEST['test'])) {
    echo 'hi';
}

trim($_REQUEST['test']) will evaluate to true or false just by itself, no empty necessary. If you actually need the trimmed value later, you can save it like so:

if (isset($_REQUEST['test']) && ($t = trim($_REQUEST['test']))) {
    echo 'hi';
}
deceze
  • 510,633
  • 85
  • 743
  • 889
1

If you make minor modification like this in your code:

if(isset($_REQUEST["test"]) && ($t=trim($_REQUEST["test"])) && !empty($t)){
   echo '1: hi<br/>';
}

if(isset($_REQUEST["test"]) && $t=trim($_REQUEST["test"])){
   if(!empty($t))
      echo '2: hi<br/>';
}

Then both 1: hi and 2: hi will be printed. Difference is parenthesis around first $t assignment.

anubhava
  • 761,203
  • 64
  • 569
  • 643