Php test if is number

What’s the correct way to test if a variable is a number in PHP?

Solution 1: Use if you want it to accept floating point values, and for integers only. Example (Try your own inputs and see how it stands up) check input value is integer or not in php php check if variable is int php check if input is int Question: I need to check if a parameter (either string or int or float) is a «large» integer.

What’s the correct way to test if a variable is a number in PHP?

When I fetch data from a database, the result is a string even if it has an number value. Here’s what I mean:

// An integer $int=10; if(is_int($int)) // Returns true . // A string $int='10'; if(is_int($int)) // Returns false . 

I want both of these to return true.

Use is_numeric() if you want it to accept floating point values, and ctype_digit() for integers only.

You can not enclose a variable with quote (single or double quote),
anything enclosed by quote will be treated as string

Everything return by database (assume is mysql) is always STRING,
for your case, it will be a NUMERIC STRING
function is_numeric (like the rest has mentioned) is the right way to go

is_numeric — Finds whether a variable is a number or a numeric string

I little hack-ish, but may be a more forceful way to check if the value «matches an integer’s pattern». By that I mean it may /may not be cast explicitly to an integer, but it has all the makings of one.

Example (Try your own inputs and see how it stands up)

Check if variable contains integer php Code Example, check input value is integer or not in php ; 1. // to check the input integer validation we can use is_int() function ; 2. Syntax: ; 3. is_int(

Check input value is integer or not in php

// to check the input integer validation we can use is_int() function Syntax: is_int(parameter); $x = 10; //returns true $x = "123"; //returns false $x = 12.365; //returns false $x = "ankur"; //returns false is_int($x);
// Check if variable is int $id = "1"; if(!intval($id)) < throw new Exception("Not Int", 404); >else< // this variable is int >
$a = 5; //returns true $a = "5"; //returns false $a = 5.3; //returns false is_int($a);

PHP: How to check if variable is a «large integer», It will first check if it is numeric then check if there is no decimal in the string by checking if it found a position.

Читайте также:  Примеры задач java junior

PHP: How to check if variable is a «large integer»

I need to check if a parameter (either string or int or float) is a «large» integer. By «large integer» I mean that it doesn’t have decimal places and can exceed PHP_INT_MAX . It’s used as msec timestamp, internally represented as float.

ctype_digit comes to mind but enforces string type. is_int as secondary check is limited to PHP_INT_MAX range and is_numeric will accept floats with decimal places which is what I don’t want.

Is it safe to rely on something like this or is there a better method:

if (is_numeric($val) && $val == floor($val)) < return (double) $val; >else . 

I recommend the binary calculator as it does not care about length and max bytes. It converts your «integer» to a binary string and does all calculations that way.

BC math lib is the only reliable way to do RSA key generation/encryption in PHP, and so it can easy handle your requirement:

$userNumber = '1233333333333333333333333333333333333333312412412412'; if (bccomp($userNumber, PHP_INT_MAX, 0) === 1) < // $userNumber is greater than INT MAX >

Third parameter is the number of floating digits.

So basically you want to check if a particular variable is integer-like?

function isInteger($var) < if (is_int($var)) < // the most obvious test return true; >elseif (is_numeric($var)) < // cast to string first return ctype_digit((string)$var); >return false; > 

Note that using a floating point variable to keep large integers will lose precision and when big enough will turn into a fraction, e.g. 9.9999999999991E+36 , which will obviously fail the above tests.

If the value exceeds INT_MAX on the given environment (32-bit or 64-bit), I would recommend using gmp instead and persist the numbers in a string format.

function isInteger($var) < if (is_int($var)) < return true; >elseif (is_numeric($var)) < // will throw warning if (!gmp_init($var)) < return false; >elseif (gmp_cmp($var, PHP_INT_MAX) >0) < return true; >else < return floor($var) == $var; >> return false; > 

I did at the end of the function to check for numeric data.

It will first check if it is numeric then check if there is no decimal in the string by checking if it found a position. If it did the returned position is an int so is_int() will catch it.

(strpos($text,».»,0)==FALSE) would also work based on the strpos manual but sometimes the function seems to send nothing at all back like

could be nothing and the ==FALSE is needed.

Best way to check for positive integer (PHP)?, php’s gmp_sign() might be another easy way to check. It works for integer and numeric strings, and returns 1 if a is positive, -1 if a is

Читайте также:  Python array type string

Источник

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
?>

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

Читайте также:  Значение аргумента по умолчанию java

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() — Определяет, является ли переменная массивом

Источник

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