为何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
相关产品推荐
相关产品推荐

