Php if var is number

How to check if a variable is an integer or number in PHP: A comprehensive guide

Learn how to check if a variable is an integer or number in PHP with built-in functions like is_int() and is_numeric(), and conditions like ctype_digit(). Discover the difference between Integer and int in PHP. Improve your code today!

  • Introduction
  • is_int() Function
  • is_numeric() Function
  • Checking if a Variable is a Whole Number
  • Other Functions to Check the Type of a Variable
  • Difference between Integer and int in PHP
  • Other helpful code examples for checking if a PHP variable is an integer or number
  • Conclusion
  • How do you check if a variable is an integer?
  • How to use Is_numeric in PHP?
  • What is the difference between int and integer in PHP?
  • How to check if a string can be converted to int PHP?

If you are a PHP developer, you must have come across situations where you need to check if a variable is an integer or a number. Luckily, PHP provides several built-in functions that make it easy to check the type of a variable. In this guide, we will walk you through the different functions in PHP that can be used to check if a variable is an integer or a number.

Introduction

Before we dive into the different functions in PHP that can be used to check the type of a variable, let’s first explain what the user intent is. If you are reading this article, you are probably seeking information on how to check if a variable is an integer or a number in PHP. In this guide, we will provide a comprehensive overview of the different functions that you can use to achieve this.

is_int() Function

The first function we will look at is the is_int() function. This is a built-in PHP function that can be used to test whether the type of the specified variable is an integer or not. Here’s an example of how to use the is_int() function:

In this example, we have assigned the value 5 to the variable $var . We then use the is_int() function to test if $var is an integer. The function returns TRUE if the variable is an integer, and FALSE otherwise.

is_numeric() Function

The second function we will look at is the is_numeric() function. This is another built-in PHP function that checks whether a variable is a number or a numeric string. Here’s an example of how to use the is_numeric() function:

$var = "3.14"; if (is_numeric($var)) < echo "Variable is a number or numeric string"; >else

In this example, we have assigned the value «3.14» to the variable $var . We then use the is_numeric() function to test if $var is a number or a numeric string. The function returns TRUE if the variable is a number or a numeric string, and FALSE otherwise.

Читайте также:  Text to java string convert to

It’s worth noting that using is_numeric() to check if a variable is an integer is not recommended because it will return TRUE for numeric strings like «3.14» .

Checking if a Variable is a Whole Number

To check if a variable is a whole number, you can use a condition like ($var == (string)(int)$var) or ctype_digit($var) . Here are examples of how to use these conditions to check if a variable is a whole number:

$var = 10; if ($var == (string)(int)$var) < echo "Variable is a whole number"; >else
$var = "10"; if (ctype_digit($var)) < echo "Variable is a whole number"; >else

In the first example, we convert $var to an integer using (int)$var . We then convert it back to a string using (string)(int)$var . If the original value of $var was a whole number, the string value will be the same as the original value. We then compare the string value to the original value using the == operator.

In the second example, we use the ctype_digit() function to check if the variable $var contains only digits.

Other Functions to Check the Type of a Variable

Apart from is_int() and is_numeric() , there are other functions that you can use to check the type of a variable in PHP. These include gettype() , is_string() , is_float() , isset() , and empty() . Here’s a brief explanation of each function:

  • gettype() : Returns the type of the specified variable.
  • is_string() : Checks whether the type of the specified variable is a string.
  • is_float() : Checks whether the type of the specified variable is a float.
  • isset() : Checks whether a variable is set and is not NULL.
  • empty() : Checks whether a variable is empty.

Here’s an example of how to use the gettype() function:

This will output integer , which is the type of the variable $var .

Difference between Integer and int in PHP

Before we wrap up this guide, let’s explain the difference between an Integer and an int in PHP. Integer is a wrapper class whereas int is a primitive data type. A wrapper class is a class that encapsulates a primitive data type, whereas a primitive data type is a basic data type that is not defined in terms of other data types.

Here’s an example of how to use Integer and int in PHP:

$var1 = new Integer(5); $var2 = 5;if ($var1 == $var2) < echo "Variables are equal"; >else

In this example, we create an Integer object with a value of 5 and assign it to $var1 . We then assign the integer value 5 to $var2 . We then compare the two variables using the == operator. Since Integer is a wrapper class, we can use the == operator to compare it with an int value.

Other helpful code examples for checking if a PHP variable is an integer or number

In Php as proof, php is variable a number code example

In Php , php check if variable is int code example

// Check if variable is int $id = "1";if(!intval($id)) < throw new Exception("Not Int", 404); >else< // this variable is int >

In Php , for example, php is int code example

Читайте также:  htmlbook.ru - Как правильно писать заголовок страницы

In Php case in point, php is_int code sample

 ?> /* Output is_int(23) = bool(true) is_int('23') = bool(false) is_int(23.5) = bool(false) is_int('23.5') = bool(false) is_int(NULL) = bool(false) is_int(true) = bool(false) is_int(false) = bool(false) */ 

In Php , php check if string is integer code sample

Conclusion

In this guide, we have provided a comprehensive overview of the different functions in PHP that can be used to check if a variable is an integer or a number. We have explained how to use is_int() and is_numeric() functions, how to check if a variable is a whole number, and other functions that can be used to check the type of a variable. We have also explained the difference between Integer and int in PHP. It’s important to choose the right function to check the type of a variable in PHP. We hope this guide has been helpful, and that you can use the tips and examples provided to improve your code.

Источник

is_int

Finds whether the type of the given variable is integer.

Note:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric() .

Parameters

The variable being evaluated.

Return Values

Returns true if value is an int , false otherwise.

Examples

Example #1 is_int() example

$values = array( 23 , «23» , 23.5 , «23.5» , null , true , false );
foreach ( $values as $value ) echo «is_int(» ;
var_export ( $value );
echo «) color: #007700″>;
var_dump ( is_int ( $value ));
>
?>

The above example will output:

is_int(23) = bool(true) is_int('23') = bool(false) is_int(23.5) = bool(false) is_int('23.5') = bool(false) is_int(NULL) = bool(false) is_int(true) = bool(false) is_int(false) = bool(false)

See Also

  • is_bool() — Finds out whether a variable is a boolean
  • is_float() — Finds whether the type of a variable is float
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_string() — Find whether the type of a variable is string
  • is_array() — Finds whether a variable is an array
  • is_object() — Finds whether a variable is an object

User Contributed Notes 30 notes

I’ve found that both that is_int and ctype_digit don’t behave quite as I’d expect, so I made a simple function called isInteger which does. I hope somebody finds it useful.

function isInteger ( $input ) return( ctype_digit ( strval ( $input )));
>

var_dump ( is_int ( 23 )); //bool(true)
var_dump ( is_int ( «23» )); //bool(false)
var_dump ( is_int ( 23.5 )); //bool(false)
var_dump ( is_int ( NULL )); //bool(false)
var_dump ( is_int ( «» )); //bool(false)

var_dump ( ctype_digit ( 23 )); //bool(true)
var_dump ( ctype_digit ( «23» )); //bool(false)
var_dump ( ctype_digit ( 23.5 )); //bool(false)
var_dump ( ctype_digit ( NULL )); //bool(false)
var_dump ( ctype_digit ( «» )); //bool(true)

var_dump ( isInteger ( 23 )); //bool(true)
var_dump ( isInteger ( «23» )); //bool(true)
var_dump ( isInteger ( 23.5 )); //bool(false)
var_dump ( isInteger ( NULL )); //bool(false)
var_dump ( isInteger ( «» )); //bool(false)
?>

Keep in mind that is_int() operates in signed fashion, not unsigned, and is limited to the word size of the environment php is running in.

is_int ( 2147483647 ); // true
is_int ( 2147483648 ); // false
is_int ( 9223372036854775807 ); // false
is_int ( 9223372036854775808 ); // false
?>

In a 64-bit environment:

is_int ( 2147483647 ); // true
is_int ( 2147483648 ); // true
is_int ( 9223372036854775807 ); // true
is_int ( 9223372036854775808 ); // false
?>

Читайте также:  Стандартные функциональные интерфейсы java

If you find yourself deployed in a 32-bit environment where you are required to deal with numeric confirmation of integers (and integers only) potentially breaching the 32-bit span, you can combine is_int() with is_float() to guarantee a cover of the full, signed 64-bit span:

$small = 2147483647 ; // will always be true for is_int(), but never for is_float()
$big = 9223372036854775807 ; // will only be true for is_int() in a 64-bit environment

if( is_int ( $small ) || is_float ( $small ) ); // passes in a 32-bit environment
if( is_int ( $big ) || is_float ( $big ) ); // passes in a 32-bit environment
?>

Simon Neaves was close on explaining why his function is perfect choice for testing for an int (as possibly most people would need). He made some errors on his ctype_digit() output though — possibly a typo, or maybe a bug in his version of PHP at the time.

The correct output for parts of his examples should be:

var_dump ( ctype_digit ( 23 )); //bool(false)
var_dump ( ctype_digit ( «23» )); //bool(true)
var_dump ( ctype_digit ( 23.5 )); //bool(false)
var_dump ( ctype_digit ( NULL )); //bool(false)
var_dump ( ctype_digit ( «» )); //bool(false)
?>

As you can see, the reason why using *just* ctype_digit() may not always work is because it only returns TRUE when given a string as input — given a number value and it returns FALSE (which may be unexpected).

With this function you can check if every of multiple variables are int. This is a little more comfortable than writing ‘is_int’ for every variable you’ve got.

function are_int ( ) $args = func_get_args ();
foreach ( $args as $arg )
if ( ! is_int ( $arg ) )
return false ;
return true ;
>

// Example:
are_int ( 4 , 9 ); // true
are_int ( 22 , 08, ‘foo’ ); // false
?>

Источник

is_numeric

Проверяет, является ли данная переменная числом. Строки, содержащие числа, состоят из необязательного знака, любого количества цифр, необязательной десятичной части и необязательной экспоненциальной части. Так, +0123.45e6 является верным числовым значением. Шестнадцатеричная (0xFF), двоичная (0b10100111001) и восьмеричная (0777) записи также допускаются, но только без знака, десятичной и экспоненциальной части.

Список параметров

Возвращаемые значения

Возвращает TRUE , если var является числом или строкой, содержащей число, в противном случае возвращается FALSE .

Примеры

Пример #1 Примеры использования is_numeric()

$tests = array(
«42» ,
1337 ,
0x539 ,
02471 ,
0b10100111001 ,
1337e0 ,
«not numeric» ,
array(),
9.1
);

foreach ( $tests as $element ) if ( is_numeric ( $element )) echo «‘ < $element >‘ — число» , PHP_EOL ;
> else echo «‘ < $element >‘ — НЕ число» , PHP_EOL ;
>
>
?>

Результат выполнения данного примера:

'42' - число '1337' - число '1337' - число '1337' - число '1337' - число '1337' - число 'not numeric' - НЕ число 'Array' - НЕ число '9.1' - число

Смотрите также

  • ctype_digit() — Проверяет на наличие цифровых символов в строке
  • is_bool() — Проверяет, является ли переменная булевой
  • is_null() — Проверяет, является ли значение переменной равным NULL
  • is_float() — Проверяет, является ли переменная числом с плавающей точкой
  • is_int() — Проверяет, является ли переменная переменной целочисленного типа
  • is_string() — Проверяет, является ли переменная строкой
  • is_object() — Проверяет, является ли переменная объектом
  • is_array() — Определяет, является ли переменная массивом

Источник

Оцените статью