php - 为什么将两个值作为字符串进行比较?
问题描述
有问题两天解决不了。我想比较两个代表年份的值。首先是用户提交的字符串 - 仅包含 4 位数字。第二个是来自date('Y')
函数的字符串,也是 4 位数字。我想检查一年我是否比另一年更好。但如果 $string 的字符数多于 date 函数的结果,则比较结果为 true。即使我将两个字符串都转换为整数。我也尝试过使用intval
函数进行转换。在比较之前,我已经检查gettype()
了这两种情况下的两个值,它们是相同的类型。有趣的是,如果我把这段代码放到 phpfiddle 中,它就像我想要的那样工作。
$string = '2020';
$isTooBig = $string > date('Y');
$isTooBig1 = (int)$string > (int)date('Y');
//In this case $isTooBig is boolean with 0 value;
完整代码:
function whatIsWrong( $type, $string ) {
$comma = '';
$json = '';
if ( $type == 'year' ) {
$yearOverLimit = $string > date('Y') && strlen($string) == 4; //problem is here
$fieldIsEmpty = strlen( $string ) == 0;
$charIsWrong = !preg_match( '/^\d{4}$/', $string ) && !strlen($string) == 0;
$json .= ' [';
if ( $fieldIsEmpty ) {
if ( $yearOverLimit || $charIsWrong ) {
$comma = ', ';
} else {
$comma = '';
}
$json .= '{"message": "Year can\'t be empty"}'.$comma;
}
if ( $yearOverLimit ) {
if ( $charIsWrong ) {
$comma = ', ';
} else {
$comma = '';
}
$json .= '{"message": "Year must be between 1870-'.date('Y').'"}'.$comma;
}
if ( $charIsWrong ) {
$json .= '{"message": "Year must be 4-digit"}';
}
$json .= ']';
}
return $json;
}
解决方案
@Werner 说:“
因此
$yearOverLimit
,只有$string > 2018 (curr yr)
4 位数字才会成立。
我知道,它应该是,这是我的意图。但它不在我的编辑器(vim)中,也不知道为什么。
(int)$string > (int)date('Y')
(不带strlen
)false
如果 year 是 YYYY 中的任何一个,则返回,true
如果 YYYYY 或更多则返回。我真笨。也许是PHP版本差异?
推荐阅读
- excel - 跳过函数错误并继续下一次检查 (VLOOKUP)
- java - 如何在创建时填充 Java 地图
- python - 从 websockets ws_handler 访问服务器上下文
- php - 如何中止 PrePersist 函数的查询执行?
- c++ - 将前 n 个素数保存在数组中而不覆盖它
- python - Shell脚本在目录中找到文件,如何传递给python脚本
- .net - 在 WPF 应用程序 (.NET Core) 中绘图会引发运行时错误
- javascript - 如何检测超出特定范围的散焦?
- typescript - 结构类型与联合失败?
- ios - 使用情节提要更改分段控制位置