php判斷是否爲數字

判斷是否爲數字

使用is_numeric函數,可以判斷數字或者數字字符串

$variables = [
    0,
    36,
    3.6,
    .36,
    '36',
    'a36',
    044, //8進制
    0x24, //16進制
    1337e0
];

結果

int(0) is number : Y // 0
int(36) is number : Y // 36
float(3.6) is number : Y // 3.6
float(0.36) is number : Y  // .36
string(2) "36" is number : Y // '36'
string(3) "a36" is number : N // 'a36'
int(36) is number : Y // 044
int(36) is number : Y // 0x24
float(1337) is number : Y // 1337e0

判斷是否爲整數

使用filter_var($v, FILTER_VALIDATE_INT) === false,這個方法可以支持整數字符串(is_int和is_integer不支持判斷整數字符串)

$variables = [
    0,
    36,
    3.6,
    .36,
    '36',
    'a36',
    044, //8進制
    0x24, //16進制
    1337e0,
    1337e-1
];

foreach ($variables as $v)
{
    $str = var_dump($v).'is integer :';
   //注意filter_var如果匹配的話將返回匹配的值,注意0的情況
    if (filter_var($v, FILTER_VALIDATE_INT) === false) {
        echo "{$str} N";
    }
    else {
        echo "{$str} Y";
    }
    
    echo "<br>";
}

結果

int(0) is integer : Y // 0
int(36) is integer : Y // 36
float(3.6) is integer : N // 3.6
float(0.36) is integer : N // .36
string(2) "36" is integer : Y //'36'
string(3) "a36" is integer : N // 'a36'
int(36) is integer : Y // 044
int(36) is integer : Y // 0x24
float(1337) is integer : Y //1337e0
float(133.7) is integer : N //1337e-1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章