-3

I faced this problem multiple times and now I'm thinking about the best solution of the following problem:

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

dump("5");

Will dump string "5". Numeric values are often given to functions whatsoever as string. I'm facing this often in Symfony 2, but also in other, native, PHP projects.

Checking if this ID is numeric would be failing in this case

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

dump("5"); // Would fail

So you could say 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

But this isn't correct because of the following behaviour of PHP.

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

So

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"); 

Which is problematic.

So by now I have the following work-around:

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"); 

Is there a better way to solve this problem, a way given in the core of PHP that I just don't know?

KhorneHoly
  • 4,666
  • 6
  • 43
  • 75

1 Answers1

6

PHP has an is_numeric() function which does just this.

bool is_numeric ( mixed $var )

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.

So in your case:

if ( is_numeric($id) ) {
    // $id is numeric
}
else {
    // $id is not numeric
}
Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218