PHP Example of methods for determining whether a variable is an integer or a positive integer
- 2021-12-21 04:18:06
- OfStack
Determine whether a variable is an integer in PHP
When writing PHP code, I encountered such a small problem: how to judge whether a variable is an integer, so I found two methods to solve it on the Internet, and made a small record here.
Method 1
<?php
$num=12; // Return right
//$num=12.1 Return false
if(is_int($num)){
echo "right";
}else{
echo "false";
}
?>
Here, the is_int () method is used to judge whether the passed parameter is an integer (int), instead of whether it is an integer, which is slightly limited.
Method 2
<?php
$num=12;
if(floor($num)==$num){
echo "right";
}else{
echo "false";
}
?>
The floor () method rounds the incoming parameters by 4 and 5. Compare the value after rounding 4 or entering 5 with the original value. If it is equal, it is an integer, and if it is not equal, it is not an integer.
php determines whether a variable is a positive integer
Method 1:
if(preg_match("/^[1-9][0-9]*$/" ,$amount)){
die(' Is a positive integer ');
}
Method 2:
$ num = '45 .7' ;
if (( floor ( $ num ) - $ num )! == 0 ) {
exit (" Not a positive integer! ") ;
} else {
exit (" Is a positive integer! ") ;
}
Method 3:
$ num = '12' ;
if ( floor ( $ num ) == $ num ) {
exit (" Is a positive integer! ") ;
} else {
exit (" Not a positive integer! ") ;
}
Method 4:
if (! is_numeric ( $ jp_total ) || strpos ( $ jp_total , ".")! == false ) {
die (" Is not an integer ") ;
} else {
die (" Is an integer ") ;
}
Summarize