PHP:带有可能为空变量的条件语句
我正在创建一个自定义搜索表单,当我尝试对结果进行排序时,我会显示所有对象而不是匹配的条件。我发现的原因是表单中的某些输入没有默认值,并且当稍后在条件语句中未声明默认值(用于排序)时,它只会显示所有对象,无论是否满足其他要求或不是。我尝试应用 OR 语句,其中特定变量可以为空,但它给出了相同的结果。就像这样 -
<?php if ($bedrooms >= $min_rooms
&& $bedrooms <= $max_rooms
&& $space >= $min_space
&& $space <= $max_space
&& $price >= $min_price
&& $price <= $max_price
&& $sel_type == $type
|| $sel_type == ''
&& $country == $sel_country
|| $sel_country == '' ) { ?>
(参见最后两个陈述) 我正在考虑在包含条件语句之前检查条件语句中的每个变量,但感觉像是不必要的代码。你会怎么做?
I'm creating a custom search form and when I try and sort the results I get all the objects displayed instead of the matched criteria. The reason I discovered was that some of the inputs from the form don't have a default value and when this is not declared in the conditional statement later on (for sorting) it just shows all the objects, whether the other requirements are met or not. I tried applying an OR statement with the specific variables able to be empty, but it gave the same result. Like so -
<?php if ($bedrooms >= $min_rooms
&& $bedrooms <= $max_rooms
&& $space >= $min_space
&& $space <= $max_space
&& $price >= $min_price
&& $price <= $max_price
&& $sel_type == $type
|| $sel_type == ''
&& $country == $sel_country
|| $sel_country == '' ) { ?>
(See the last two statements)
I was thinking of checking each variable in the conditional statement before including it but it feels like unnecessary code. How would you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
&&
运算符的优先级高于||
运算符,因此您的表达式当前按如下方式分组,可能不是您想要的:尝试添加这样的括号实现正确分组:
The
&&
operator has a higher precedence than the||
operator, so your expression is currently grouped like this, probably not what you want:Try adding parentheses like this to achieve correct grouping:
您的表达式可能会失败,因为
&&
运算符具有更高的优先级 比||
操作。这意味着像这样的表达式:等价于此(通过使用括号突出显示运算符优先级):
要解决此问题,请将
||
表达式放在括号中:此外,您的表达式可能更易于阅读和维护如果您使用一些辅助函数,例如
Between 函数:
那么您的表达式将显示为:
Your expression may fail as the
&&
operator has a higher precedence than the||
operation. That means an expression like this:is equivalent to this (operator precedence highlighted by using parentheses):
To fix that put the
||
expressions in parentheses:Additionally, your expression is probably easier to read and to maintain if you use some helper functions like a
between
function:Then your expression reads: