Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php variable assignment inside if conditional

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'
}
like image 558
user678070 Avatar asked Mar 29 '11 02:03

user678070


2 Answers

&& 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';
}
like image 81
deceze Avatar answered Oct 04 '22 00:10

deceze


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.

like image 35
anubhava Avatar answered Oct 04 '22 02:10

anubhava