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

Kho*_*oly -3 php

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

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

dump("5");
Run Code Online (Sandbox Code Playgroud)

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

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

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

dump("5"); // Would fail
Run Code Online (Sandbox Code Playgroud)

所以你可以说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
Run Code Online (Sandbox Code Playgroud)

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

$string = "test";
$string = (int)$string;
var_dump($string); // Would give out the integer value 0
Run Code Online (Sandbox Code Playgroud)

所以

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"); 
Run Code Online (Sandbox Code Playgroud)

这是有问题的.

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

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"); 
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*lly 6

PHP有一个is_numeric()功能就是这样做.

bool is_numeric ( mixed $var )

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

所以在你的情况下:

if ( is_numeric($id) ) {
    // $id is numeric
}
else {
    // $id is not numeric
}
Run Code Online (Sandbox Code Playgroud)