You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何PHP中in_array判断字符串与数组值匹配时始终返回true?

问题描述

我编写了如下PHP代码:

$specific_discount_dates = get_field('specific_discount_dates', 'options');

$specific_discount_dates_array = array();
if (have_rows('specific_discount_dates', 'options')) {
while ( have_rows( 'specific_discount_dates', 'options') ) : the_row();
    $other_discount_dates   = get_sub_field('other_discount_date');
    $date_obj               = date_create_from_format('d/m/Y', $other_discount_dates);
    $formatted_date         = date_format($date_obj, 'd-m-Y');
    array_push($specific_discount_dates_array, $formatted_date);
endwhile;
}

if (in_array($end_date, $specific_discount_dates_array)) {
    return true;
} else {
    return false;
}

当我执行echo $end_date时,输出为:28-04-2023
执行print_r($specific_discount_dates_array)时,输出为:

Array
(
    [0] => 24-04-2023
    [1] => 30-04-2023
)

然而,尽管28-04-2023并不匹配数组中的任何字符串,该条件却始终返回true,请问我忽略了什么?

问题分析与解决

问题出在in_array的默认行为上——它默认使用松散比较(==),而非严格比较(===)。

你的$end_date大概率不是纯字符串类型,而是DateTime对象。松散比较时,PHP会自动将DateTime对象转换为字符串,转换后的格式刚好和数组中的日期字符串一致,导致in_array误判为匹配。

解决方法是给in_array添加第三个参数true,启用严格比较,同时校验值和类型:

if (in_array($end_date, $specific_discount_dates_array, true)) {
    return true;
} else {
    return false;
}

额外验证建议:

  • 用var_dump($end_date)查看变量的实际类型,确认是否为字符串;
  • 检查date_create_from_format是否可能返回false(比如日期格式错误),避免无效值混入数组。

内容的提问来源于stack exchange,提问作者User_FTW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:42:35