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'
}
1
  • duplicate? Commented Mar 29, 2011 at 2:15

2 Answers 2

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';
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.