How to find whether a variable is positive integer with PHP

PHP is_numeric() is useful to find whether a variable is a number or a numeric string. How you can check if a variable is an integer?

You may use the following simple function:

<?php
/**
 * Check if expression is positive integer
 *
 * @param $str
 * @return bool
 */
function is_positive_integer($str) {
        return (is_numeric($str) && $str > 0 && $str == round($str));
}
?>

Example

With this function you can check user input, as following:

<?php

$customer_id = $_GET['customer_id'];

if(!is_positive_integer($customer_id)) {
        echo 'Given value for Customer ID is not acceptable';
        exit;
}
?>

Never trust user input to avoid SQL Injection attacks. You may use Prepared Statements when you insert user data in the database, but the first step is to sanitize user input.

Remarks

Do not confuse this function with PHP is_integer() (alias of is_int()). is_integer() finds whether the type of the given variable is integer, not the variable itself.