I have a function that is called over and over from my code where I can pass a variable and the function acts differently if the parameter is a “real” (int/float) number (in other words does not do any manipulation nor add the quotes around it when passed to a MySQL query). Currently my code does a double type check, but is there a better way ?
$a = 1;
$b = '1';
$is_num = (is_numeric($a) && !is_string($a)); //true
$is_num = (is_numeric($b) && !is_string($b)); //false
is there a better faster way to do this ?
for example (VERY simplified version):
$query = 'SELECT * FROM `table` WHERE ';
$field = 'id';
$operator = '=';
$value = 2;
$query .= '`'.$field.'`'.$operator;
$is_num = (is_numeric($value) && !is_string($value));
if($is_num){
$query .=$value;
}else{
$query .='"'.mysql_real_escape_string((string)$value).'"';
}
$query .=';';
If your number is always an integer, then you can use
is_int. If there is a possibility that it might be a decimal-point number and you want that to return$is_num == truethen no, you have to do the check as you are or check either type withis_int($a) || is_float($a)The specific purpose of
is_numericis to check if it is “numeric or a numeric string” and there is no “all number types” catch-all.However, given your comment that this is for a query builder, why not just add quotes if
is_stringand not otherwise?