I am doing this to check and already use the variable of type number in php:
$myvar = $myvar * 1;
with this, I have a number or if $myvar has any other caracter, the result is 0
I wonder if this can somehow trouble me in the future.
for preventing sake, I am using a function that englobes that above code so I can change it if needed. Eg:
$myvar = IntOrZero($myvar);
so my question if this is a goodway to check and use the number variable?
EDIT:
Using a * 1, I am sure that it will return me a variable of type number.
See:
$var = "350";
$num = 120;
// builtin
if (is_numeric($var))
echo($var - $num);
// multiplying
$var *= 1;
echo($var - $num);
While I am not sure if the builtin method would echo what I want, I am sure that the multiplying will.
I kinda don’t care if the $var is a number or not, I won’t show any message to the user if it is not, I will work with the 0 value if it is not a number. Based on answers, would this be a good way?
function IntOrZero($var){
return is_numeric($var) ? intval($var) : 0;
}
thanks,
Joe
No, it’s not a good way, and here’s why:
To make sure a variable is a number, cast it:
To check whether it’s a number or not:
These are all slightly different, depending on what exactly you want to check for. Refer to the documentation:
http://php.net/is_numeric
http://php.net/manual/en/function.ctype-digit.php
http://php.net/is_int
http://php.net/is_float