php

How to check if a variable is an Integer in PHP?

Which methods are available in PHP to check if a variable is an Integer? In this tutorial, we are going to see how to check if a variable is an Integer in PHP.
 

is_int()

The function is_int($var) returns whether the passed variable is an Integer or not:

<?php
    var_dump( is_int(1) ); // true
    var_dump( is_int(0) ); // true
    var_dump( is_int(-1) ); // true

    var_dump( is_int(1.0) ); // false
    var_dump( is_int('1') ); // false
    var_dump( is_int(true) ); // false
    var_dump( is_int(new stdClass()) ); // false
?>

Output:

bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
 

Test for Integer parameters

It makes sense to use is_int() to check function parameters:

<?php
    function square($val) 
    {
        if (!is_int($val)) 
        {
            echo("The number passed is not an integer.\n");
             
        } 
        else 
        {
            echo("Square of $val: ".($val * $val)."\n");
        }
    }
 
    square(2);
    square(0.4);
    square("StackHowTo");
    square(true);
?>

Output:

Square of 2: 4
The number passed is not an integer.
The number passed is not an integer.
The number passed is not an integer.
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *