Is it ok to multiply by one variable to check if this number is really in php?

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

+4
source share
3 answers

No, this is not good, and here's why:

 $ php -r 'echo array() * 1;' Fatal error: Unsupported operand types in Command line code on line 1 

To make sure the variable is a number, produce it :

 $integer = (int)$integer; $float = (float)$float; 

To check if this is a number or not:

 is_numeric($var) // number or string containing any valid numeric expression ctype_digit($var) // string containing only digits is_int($var) // is of type int is_float($var) // is of type float 

They are all a little different, depending on what exactly you want to check. See 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

+14
source

what is wrong with is_int () \ is_numeric () \ ctype_digit () ??

+3
source

Umm, why aren't you doing the right check?

Like:

I highly recommend you use the right way to test your value.

+2
source

Source: https://habr.com/ru/post/1338604/


All Articles