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?