开发者

php variable assignment inside if conditional

开发者 https://www.devze.com 2023-02-20 05:08 出处:网络
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?

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'
}


&& 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';
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号