Check if 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 ways 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";   
       }
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Here, the is_int() method is used to judge whether the incoming parameter is an integer (int), rather than judging whether it is an integer, which is slightly limited.

Method 2

<?php
  $num=12;
  if(floor($num)==$num){
        echo "right";
  }else{
        echo "false";   
       }
?>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

The floor() method rounds the incoming parameter. Compare the rounded or rounded value with the original value. If they are equal, they are integers, and if they are not equal, they are not integers.

Related: Check if a variable is an integer in PHP