2012-02-29 86 views
2

下面的函數使我瘋狂。 100x如何等於100,然後100x被報告爲整數?
對於我的生活,我無法弄清楚。 你可以複製和粘貼整個事情,併爲自己看。
我在這裏錯過了一個簡單的點,幫助我出去。無法確定一個字符串當前是否是一個整數

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認爲100x = 100是等於。

+0

'is_int','ctype_digit','filter_var($ string,FILTER_VALIDATE_INT)',如果需要,後者可以禁止/允許十六進制和八進制整數。如果你想使用你的代碼,大小寫爲int,但是返回字符串:'if((string)$ orgval ==(string)(int)$ orgval)' – Wrikken 2012-02-29 19:38:36

+0

你的函數使用'echo'和'return',儘量不要用這種方式寫函數。輸出是什麼?我的意思是當在int轉換之前和之後'回顯變量時,你在屏幕上看到了什麼? – 2012-02-29 19:39:39

回答

2

正如你可以看到this example,鑄造100x爲整數它轉換爲100。由於您未使用嚴格比較,'100x' == 100屬實。 PHP將x從中刪除,僅製作100

您可以使用嚴格比較(也可以比較類型),以便'100x' === 100將返回false。使用它,任何時候一個字符串與一個整數進行比較,它會返回false。


根據您的編輯:is_numeric未必是最可靠的,因爲它會爲格式化爲一個字符串的數字返回true,如'100'。如果你想要的數字是一個整數(而不是一個字符串),你可以使用is_integer來代替。我不太確定你在做什麼,但我想我會添加這個筆記。

+0

除此之外,「100'=== 100'也是錯誤的。 – Wrikken 2012-02-29 19:47:20

+0

編寫一個函數的最好方法是什麼(可能稱之爲「is_this_integer($ v)」),當$ V傳遞給它時,它返回true *看起來像是一個肉眼整數?所以,不僅是1或-1,而且還有諸如'1'或'1'或'-1'或'-1'的字符串都將返回true,並且不用說100x或'100x'將不會返回爲整數。 – 2012-03-03 14:34:24

1

你想要做什麼樣的支票?有幾種方法可以解決這個問題:

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

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

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

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

這取決於你希望檢查它是否是一個整數。如果您首先需要trim(),這有什麼關係嗎?

相關問題