首页 > 解决方案 > 为什么将两个值作为字符串进行比较?

问题描述

有问题两天解决不了。我想比较两个代表年份的值。首先是用户提交的字符串 - 仅包含 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;
}

标签: phpvalidationtypes

解决方案


@Werner 说:“

因此$yearOverLimit,只有$string > 2018 (curr yr)4 位数字才会成立。

我知道,它应该是,这是我的意图。但它不在我的编辑器(vim)中,也不知道为什么。 (int)$string > (int)date('Y') (不带strlenfalse如果 year 是 YYYY 中的任何一个,则返回,true如果 YYYYY 或更多则返回。我真笨。也许是PHP版本差异?


推荐阅读