如果有条件的话,php变量赋值 [英] php variable assignment inside if conditional

查看:94
本文介绍了如果有条件的话,php变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个如果 s产生不同的结果(第一个如果如果 echos hi,第二个没有),为什么?为什么 $ t 上的变量赋值不起作用?这是由于 $ t 中的本地范围,如果有条件的话?

The following two ifs produced different results(first if echos 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))

由于!empty($ t)在将任何内容分配给 $ 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']) 将自行评估为 true false ,无必要。如果你以后真的需要 trim med值,你可以这样保存:

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

这篇关于如果有条件的话,php变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆