php variable assignment inside if conditional

前端 未结 2 1884
挽巷
挽巷 2020-12-17 03:48

The following two ifs produced different results(first if echos hi, second does not), why? why didn\'t the variable assignment on $t

相关标签:
2条回答
  • 2020-12-17 04:29

    && 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';
    }
    
    0 讨论(0)
  • 2020-12-17 04:30

    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 讨论(0)
提交回复
热议问题