首页 > 解决方案 > 仅当变量具有值时才使用多条件 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')): 
?>

标签: phpif-statement

解决方案


您想检查每个变量是否未设置或是否等于所需值

<?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'))
 ): ?>

推荐阅读