php - 仅当变量具有值时才使用多条件 PHP IF 语句
问题描述
我有以下 if 语句,如果 example = sidebar、date start < now 和 date end > now,我想返回 TRUE。它按原样工作,但问题是如果其中一个值不存在,则该语句为假。
如果每个变量 ($position,$date_start, $date_end) isset ,如何更改语句以仅添加条件?如果未设置变量之一,则该部分条件将被忽略。例如,如果没有 date_end,它只会评估 position 和 date_start
<?php
if ($position == "sidebar" &&
$date_start < strtotime('now') &&
$date_end > strtotime('now')):
?>
解决方案
您想检查每个变量是否未设置或是否等于所需值
<?php if (
(!isset($position) || $position == "sidebar") &&
(!isset($date_start) || $date_start < strtotime('now')) &&
(!isset($date_end) || $date_end > strtotime('now'))
): ?>
如果要允许未设置、、null
(''
空字符串)和0
除指定字符串值之外的值,则可以检查empty()
而不是isset()
<?php if (
(!empty($position) || $position == "sidebar") &&
(!empty($date_start) || $date_start < strtotime('now')) &&
(!empty($date_end) || $date_end > strtotime('now'))
): ?>
推荐阅读
- python - networkx 中的 all_simple_paths 运行时间过长
- javascript - Reactjs - 在被函数告知渲染后按钮不显示
- google-cloud-platform - 如何在 Google Cloud Platform 中以编程方式(Python)附加静态 IP 地址
- python - 读取也是对象的关键节点时出现熊猫错误
- scala - 如何折叠光滑的列的总和?
- amazon-web-services - 无法访问 Elastic Beanstalk IP 地址之一?
- c# - 是否可以从 URL 将图像加载到统一画布中?
- java - 如何解决 java.lang.RuntimeException: RESTEASY007545: Unable to find a MessageBodyReader for media type
- module - 构建的内核模块不包括 ccflags -y
- laravel - 简写 isset 后跟 eval