一、 in_array(0, [‘a’, ‘b’, ‘c’])返回true
in_array(0, ['a', 'b', 'c']) // 返回bool(true),也就相当于数组中有0
array_search(0, ['a', 'b', 'c']) // 返回int(0),也就是第一个值的下标
0 == 'abc' // 返回bool(true),也就相当于相等
出现这种情况,主要是因为在比较前PHP做了类型转换,例如:
echo intval('abc') // 会输出0
解决: 使用严格比较
in_array(0, ['a','b'], true);
二、strtotime结合-1 month, +1 month的奇葩问题
echo date('Y-m-d', strtottime('-1 month', strtotime('2018-07-31'))); // 返回 2018-07-01
echo date('Y-m-d', strtotime('+1 month', strtotime("2018-08-31"))); // 返回 2018-10-01
出现这种情况,主要因为:
- 先做-1 month, 那么当前是07-31, 减去一以后就是06-31.
- 再做日期规范化, 因为6月没有31号, 所以就好像2点60等于3点一样, 6月31就等于了7月1
echo date('Y-m-d', strtotime('2017-06-31'); //返回2017-07-01 因为6月没有31号。
解决:
从PHP5.3开始呢, date新增了一系列修正短语, 来明确这个问题, 那就是”first day of” 和 “last day of”, 也就是你可以限定好不要让date自动”规范化”:
echo date('Y-m-d', strtotime('last day of -1 month', strtotime('2017-03-31')));
// 返回2017-02-28
echo date("Y-m-d", strtotime('first day of +1 month', strtotime('2017-08-31')));
// 返回2017-09-01
参考:
风雪之隅 - 令人困惑的strtotime
歪麦博客 - 为什么in_array(0, [‘a’, ‘b’, ‘c’])返回true