I do this to check and already use a variable of type number in php:
$myvar = $myvar * 1;
with this, I have a number, or if $ myvar has any other character, the result is 0
I wonder if this can somehow beat me in the future.
to prevent saki, I use a function that decodes this code above, so I can change it if necessary. For instance:
$myvar = IntOrZero($myvar);
so my question is if this is a good way to check and use a numeric variable?
EDIT:
Using * 1, I'm sure it will return me a type number variable.
Cm.:
$var = "350"; $num = 120; // builtin if (is_numeric($var)) echo($var - $num); // multiplying $var *= 1; echo($var - $num);
Although I'm not sure if the inline method will be an echo of what I want, I am sure there will be multiplication.
I donβt care if $ var is a number or not, I will not show any message to the user, if it is not, I will work with the value 0, if it is not a number. Based on the answers, would this be a good way?
function IntOrZero($var){ return is_numeric($var) ? intval($var) : 0; }
thanks,
Joe
source share