检查变量是否为数字的最佳方法

时间:2015-05-06 09:03:47

标签: php

我多次遇到这个问题,现在我正在考虑以下问题的最佳解决方案:

public function dumpID($id){
    var_dump($id);
}

dump("5");

将转储string "5"。数值通常作为字符串赋予函数。我经常在Symfony 2中面对这个问题,但在其他原生PHP项目中也是如此。

检查此ID是否为数字在这种情况下会失败

public function dumpID($id){
    if(is_int($id)){
        var_dump($id);
    } else { // throw error }
}

dump("5"); // Would fail

所以你可以说casting to int would solve this problem

public function dumpID($id){
    $id = (int)$id;
    if(is_int($id)){
        var_dump($id);
    } else { // throw error }
}

dump("5"); // Would var_dump the $id

但由于PHP的以下行为,这是不正确的。

$string = "test";
$string = (int)$string;
var_dump($string); // Would give out the integer value 0

所以

public function dumpID($id){
    $id = (int)$id;
    if(is_int($id)){
        var_dump($id);
    } else { // throw error }
}

// Would var_dump out the integer value 0 
//and the if condition succeed even if the given value is a string!
dump("test"); 

哪个有问题。

所以现在我有以下解决方法:

public function dumpID($id){
    $id = (int)$id;
    if($id == (string)(int)$id){
        var_dump($id);
    } else { // throw error }
}

// Would throw an error because 0 != "test"
dump("test"); 

有没有更好的方法来解决这个问题,这是PHP的核心中我不知道的一种方式?

1 个答案:

答案 0 :(得分:5)

PHP有an is_numeric() function就是这样做的。

  

bool is_numeric ( mixed $var )

     

查找给定变量是否为数字。数字字符串由可选符号,任意数量的数字,可选的小数部分和可选的指数部分组成。因此+ 0123.45e6是有效的数值。也允许使用十六进制(例如0xf4c3b00c),二进制(例如0b10100111001),八进制(例如0777)表示法,但只能使用符号,十进制和指数部分。

所以在你的情况下:

if ( is_numeric($id) ) {
    // $id is numeric
}
else {
    // $id is not numeric
}