문제

다음 funciton은 나를 끌어 냈습니다.지구 100 배가 100과 같을 수있는 방법은 100 배가 정수로보고됩니까? 나의 삶을 위해, 나는 그것을 알아낼 수 없다. 당신은 모든 것을 복사하여 붙여 넣고 자신을 위해 그것을 볼 수 있습니다.
어딘가에있는 간단한 지점을 놓치고, 나를 도와주세요.

function blp_int($val) {
    $orgval = $val;
    $num = (int)$val;    
    echo "<li><font color=red>val: ". $val . " is being checked to see if it's an integer or not";
    echo "<li><font color=red>orgval: ". $orgval ;
    echo "<li><font color=red>num: ". $num ;
    if ($orgval==$num) {
        echo "<li><font color=red><b>YES IT IS! the [{$orgval}] is equal to [{$num}]</b>";
        return true;
    }
    return false;
}

if (blp_int("100"))
{
    echo "<h1>100 is an integer!</h1>";
}
else
{
    echo "<h1>100 is NOT an integer!</h1>";
}

if (blp_int("100x"))
{
    echo "<h1>100x is an integer!</h1>";
}
else
{
    echo "<h1>100x is NOT an integer!</h1>";
}
.

위의 코드는 다음을 반환합니다.

val: 100 is being checked to see if it's an integer or not
orgval: 100
num: 100
YES IT IS. the [100] is equal to [100]
100 is an integer!

val: 100x is being checked to see if it's an integer or not
orgval: 100x
num: 100
YES IT IS. the [100x] is equal to [100]
100x is an integer!
.

다음 비트를 추가하여 상황을 해결할 수 있습니다

    if (!is_numeric($val))
    {
        return false;
    }
.

BLP_INT 기능의 맨 위로 바로 박쥐가 바로 떨어져 있지만, 지구의 PHP가 100 배= 100이 같다고 생각하는 이유를 알아내는 것은 아직도 호기심입니다.

도움이 되었습니까?

해결책

As you can see in this example, casting 100x as an integer converts it to 100. Since you are not using strict comparison, '100x' == 100 is true. PHP removes the x from it to make just 100.

You could use strict comparison (which also compares the types), such that '100x' === 100 would return false. Using it, any time a string was compared to an integer, it would return false.


As per your edit: is_numeric may not be the most reliable, as it will return true for numbers formatted as a string, such as '100'. If you want the number to be an integer (and never a string), you could use is_integer instead. I'm not quite sure what exactly you're doing, but i thought I'd add this note.

다른 팁

I think you should use three equal signs in your IF:

if ($orgval===$num) {

Otherwise PHP casts the value 100x to 100 and 100=100.

Documentation: Comparison Operators

What kind of check do you want to do? There are a few ways you could go about it:

if (preg_match('!^[0-9]+$!', $input))

if (intval($input) == $input)

if (intval($input) === $input)

if ('x'.intval($input) === 'x'.$input)

It depends on how closely you want to check if it's an integer. Does it matter if you need to trim() it first?

Either cast it to an int or try http://php.net/manual/en/function.ctype-digit.php. You also need === in your if.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top