PHP - is_numeric () use necessary or can use comparison signs for all positive numeric cases?

It seems that simple comparative signs >,>=and their inverse components can evaluate whether a particular variable is a number or not. Example$whatami='beast'; ($whatami<0)?echo 'NaN':echo 'is numeric!';

Are there cases where use is is_numeric()necessary for positive values ​​(number> 0) ? It seems that using the above signs will determine if the variable is numeric.

+3
source share
4 answers

As I found out, many of these helper functions are really necessary because PHP is not very typed. I posted a similar question (albeit not one that is similar) to isset earlier this week. It should be noted that PHP will change your string to its integer value for comparison in some cases (if there are mixed types). This cannot be ignored. I think this is a strong argument foris_numeric

from PHP manual

If you are comparing a number with a string or the comparison includes numerical strings, then each string is converted to a number and the comparison is performed numerically. These rules also apply to the switch statement. Type conversion does not require space when comparing === or! ==, as this includes a comparison of the type as well as the value.

, , , " 0" PHP. . . , false, .. .

:

:

$whatami='beast';  
($whatami<5) ? echo 'less than 5' : echo 'more than 5';

PHP "" , . . - , :

$whatami='beauty';  
if(is_numeric($whatami){
    ($whatami<5) ? echo 'less than 5' : echo 'more than 5';
} else {
    exit('what, am I not pretty enough for a beast?');
}

( ).

+5

" , " ", ". , ( > <= >= <) . is_numeric , , , .

, 0, , . :)

: , is_numeric , 0. is_numeric, . , 0 , is_numeric, . , :

, > , >= , - -

, is_numeric() ( > 0)? -

, , - . , , .

+2

.

, PHP . , , , is_numeric() . ,

echo (is_numeric($whatami) && $whatami < 0) ? 'number greater than zero' : 'NaN or negative';

. , , .

0

, .

:

var_dump("5aa" > 4); //bool(true)
var_dump("5aa" > 6); //bool(false)

, "5aa" int(5). , is_numeric:

var_dump(is_numeric("5aa")); //bool(false)

, is_numeric . , .

Please note that cases when a numeric string and a number are not exactly the same:

var_dump("255" & "2"); //string(1) "2" 
var_dump(255 & 2); //int(2)

See bitwise operations :

Be aware of data type conversions. If both left and right parameters are strings, the bitwise operator will work with ASCII character values.

0
source

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


All Articles