簡體   English   中英

PHP代碼檢查數組是否為數字不起作用

[英]PHP code to check if array is numeric is not working

我有以下PHP:

 <?php

 $array = array("1","2","3");
 $only_integers === array_filter($array,'is_numeric'); // true

 if($only_integers == TRUE)
 {
 echo 'right';
 }

 ?>

由於某種原因,它始終不返回任何內容。 我不知道我在做什么錯。

謝謝

is_int檢查變量的實際類型,在您的情況下為string 不管變量類型如何,都將is_numeric用於數值。

請注意,以下所有值均被視為“數字”:

"1"
1 
1.5
"1.5"
"0xf"
"1e4"

也就是說,任何有效的浮點數或整數表示形式的浮點數,整數或字符串。

編輯:另外,您可能會誤解了array_filter ,它不會返回true或false,而是一個新數組,其中所有具有回調函數返回true的值。 if($only_integers)仍然可以工作(在您固定分配運算符之后),因為所有非空數組都被視為“真假”。

編輯2:正如@SDC所指出的,如果只想允許使用十進制格式的整數,則應使用ctype_digit

您必須將原始數組的長度與過濾后的數組的長度進行比較。 array_filter函數返回一個數組,該數組的值與將filter設置為true的值匹配。

http://php.net/array_filter

 if(count($only_integers) == count($array))  {
     echo 'right';
 } else {
     echo 'wrong';
 }
  1. is_int()對於字符串"1"將返回false
    我看到您現在已編輯問題以使用is_numeric()代替; 這可能也是一個壞主意,因為對於十六進制和指數值,它會返回true ,而您可能不希望這樣做(例如is_numeric("dead")將返回true)。
    我建議改用ctype_digit()

  2. 三重相等在這里被濫用。 它用於比較,而不是分配,因此永遠不會設置$only_integers 使用單等於設置$only_integers

  3. array_filter()不返回true / false值; 它返回數組,並刪除過濾后的值。 這意味着隨后的$only_integers為true的檢查將不起作用。

  4. $only_integers == TRUE 沒關系,但是您可能應該在這里使用三等式。 但是當然,我們已經知道$only_integers不會是truefalse ,而是一個數組,因此實際上我們需要檢查它是否包含任何元素。 count()可以解決問題。

考慮到所有這些,代碼就是這樣的……

 $array = array("1","2","3");
 $only_integers = array_filter($array,'ctype_digit'); // true

 if(count($only_integers) > 0)
 {
     echo 'right';
 }

=更改===用來比較不用於初始化變量

<?php

 $array = array(1,2,3);
 $only_integers = array_filter($array,'is_int'); // true

 if($only_integers == TRUE)
 {
 echo 'right';
 }

?>

在發布之前,您是否嘗試運行代碼? 我有這個錯誤:

Notice: Undefined variable: only_integers in ~/php/test.php on line 4
Notice: Undefined variable: only_integers in ~/php/test.php on line 6

===更改為=解決問題。 您最好學習如何使用phplint和其他工具來避免像這樣的拼寫錯誤。

<?php
$test1 = "1";
if (is_int($test1) == TRUE) {
    echo '$test1 is an integer';
}
$test2 = 1;
if (is_int($test2) == TRUE) {
    echo '$test2 is an integer';
}
?>

嘗試此代碼,您將了解為什么您的代碼不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM