php проверка целое число или нет
Проверка, является ли переменная целым числом в PHP
У меня есть следующий код
который я собираюсь использовать для просмотра разных «страниц» базы данных (результаты 1-10, 11-20 и т. д.). Однако я не могу заставить функцию is_int() работать правильно. Ввод «1» в url (noobs.РНР?p=1) дает мне ошибку недопустимой страницы, а также что-то вроде «asdf».
12 ответов
используя is_numeric() для проверки, является ли переменная целым числом, это плохая идея. Эта функция будет возвращать TRUE на 3.14 например. Это не ожидаемое поведение.
чтобы сделать это правильно, вы можете использовать один из следующих вариантов:
учитывая этот массив переменных:
первый вариант (FILTER_VALIDATE_INT путь):
второй вариант (литье Способ сравнения):
третий вариант (CTYPE_DIGIT путь):
четвертый вариант (REGEX way):
вы можете увидеть это, позвонив var_dump :
используя is_numeric обеспечит желаемый результат (имейте в виду, что позволяет такие значения, как: 0x24 ).
когда браузер посылает p в строке запроса он принимается как строка, а не int. всегда будет возвращать false.
вместо is_numeric() или ctype_digit()
/!\ Best anwser неверно, is_numeric() возвращает true для целого числа и всех числовых форм, таких как «9.1»
PS: Я знаю, что это старый пост, но все же третий в google ищет «php-целое число»
просто для удовольствия я протестировал несколько из упомянутых методов, плюс один, который я использовал в качестве решения в течение многих лет, когда я знаю, что мой вход является положительным числом или строковым эквивалентом.
Я проверил это со 125,000 итерациями, с каждой итерацией, проходящей в том же наборе типов переменных и значений.
Способ 1: 0.0552167892456
Способ 2: 0.126773834229
Способ 3: 0.143012046814
Способ 4: 0.0979189872742
Метод 5: 0.112988948822
Способ 6: 0.0858821868896
(я даже не проверить регулярное выражение, я имею в виду, серьезно. regex для этого?)
Примечание:
Метод 4 всегда возвращает false для отрицательных чисел (отрицательное целое число или строковый эквивалент), поэтому хороший метод последовательно обнаруживает, что значение является положительным целым числом.
Метод 1 возвращает true для отрицательного целого числа, но false для строкового эквивалента отрицательного целого числа, поэтому не используйте этот метод, если вы не уверены, что ваш вход никогда не будет содержать отрицательное число в строке или целочисленная форма, и если это так, ваш процесс не будет нарушать это поведение.
код, используемый для получения вывода выше:
is_float
(PHP 4, PHP 5, PHP 7, PHP 8)
is_float — Проверяет, является ли переменная числом с плавающей точкой
Описание
Проверяет, является ли данная переменная числом с плавающей точкой.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования is_float()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 10 notes
Coercing the value to float and back to string was a neat trick. You can also just add a literal 0 to whatever you’re checking.
( «5.0» + 0 ); // true
isfloat ( «5.0» ); // false
isfloat ( 5 + 0 ); // false
isfloat ( 5.0 + 0 ); // false
isfloat ( ‘a’ + 0 ); // false
?>
YMMV
If you want to test whether a string is containing a float, rather than if a variable is a float, you can use this simple little function:
function isfloat($f) return ($f == (string)(float)$f);
Boylett’s solution is elegant (http://php.net/manual/en/function.is-float.php#85848), but won’t work for long float’s or variables that are not explicitly type of ‘string’ or for long floats that are encased in quotes, making it a string that will be truncated/rounded when cast to a float. So, further logic must be completed to test for the case. Take the following example:
if (! function_exists ( «test_float» )) <
Why is it not working now, but the value is truly a float? Same reasoning as mentioned before. The float is so long that it’s truncated/rounded and doesn’t match the comparison being done with the short-hand function.
So, as you can see, more logic should be applied to the variable you’re testing.
As celelibi at gmail dot com stated, is_float checks ONLY the type of the variable not the data it holds!
If you want to check if string represent a floating point value use the following regular expression and not is_float(),
or poorly written custom functions.
Yet another regular expression for float in real life:
PHP проверка на число
Как в php проверить является ли переменная целым положительным число. Именно целым (дробное не допускается), т.е. функция is_numeric не подходит. ( is_int тоже не подходит )
14 ответов 14
P.S: Существует бесконечное кол-во способов решения вашего туманно сформулированного вопроса
Уже предложена куча вариантов, но я бы наверное сделал так
как вариант проверь сначала is_numeric, а потом проверь что в строке отсутствуют знаки ‘+’ и ‘.’ и ‘,’
Мне нравится такое решение, всегда использую:
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.9.17.40238
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
is_int
(PHP 4, PHP 5, PHP 7, PHP 8)
is_int — Проверяет, является ли переменная целым числом
Описание
Проверяет, является ли тип переменной целочисленным.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования is_int()
Результат выполнения данного примера:
Смотрите также
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.
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)
?>
The correct output for parts of his examples should be:
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.
In a 32-bit environment:
( 2147483647 ); // true
is_int ( 2147483648 ); // false
is_int ( 9223372036854775807 ); // false
is_int ( 9223372036854775808 ); // false
?>
In a 64-bit environment:
( 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:
= 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
I’ve found a faster way of determining an integer.
On my env, this method takes about half the time of using is_int().
Cast the value then check if it is identical to the original.
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.
Simon Neaves’s answer is incomplete: negative integers will return false.
is_numeric
(PHP 4, PHP 5, PHP 7, PHP 8)
is_numeric — Проверяет, является ли переменная числом или строкой, содержащей число
Описание
Определяет, является ли данная переменная числом или строкой, содержащей число.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Примеры использования is_numeric()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 40 notes
If you want the numerical value of a string, this will return a float or int value:
Note that the function accepts extremely big numbers and correctly evaluates them.
So this function is not intimidated by super-big numbers. I hope this helps someone.
PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
for strings, it return true only if float number has a dot
is_numeric( ‘42.1’ )//true
is_numeric( ‘42,1’ )//false
I think that is best check solution if u want to create real calculator for example 🙂
is_number ( 12 ); // true
is_number (- 12 ); // true
is_number (- 12.2 ); // true
is_number ( «12» ); // true
is_number ( «-124.3» ); // true
is_number ( 0.8 ); // true
is_number ( «0.8» ); // true
is_number ( 0 ); // true
is_number ( «0» ); // true
is_number ( NULL ); // false
is_number ( true ); // false
is_number ( false ); // false
is_number ( «324jdas32» ); // false
is_number ( «123-» ); // false
is_number ( 1e7 ); // true
is_number ( «1e7» ); // true
is_number ( 0x155 ); // true
is_number ( «0x155» ); // false
?>
check if given string is mobile number
Referring to previous post «Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,’lang’) or set_locale(LC_NUMERIC,’lang’)»:
This is totally wrong!
This was the example code:
——
set_locale(LC_NUMERIC,’fr’);
is_numeric(12.25); // Return False
is_numeric(12,25); // Return True
is_float(12.25); //Return False
is_float(12,25); //Return True
——
— set_locale() does not exist, you must use setlocale() instead
— you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
— if you don’t enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE
—-
setlocale(LC_NUMERIC,’fr’);
is_numeric(12.25); // Return True
is_numeric(«12,25»); // Return False
is_float(12.25); //Return True
is_float(«12,25»); //Return False
—-
Remarks:
— is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a «value») and the way PHP interpretes files is definitely _not_ affected by the locale
— is_float(«12,25») is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats
And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both «numeric».
I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.
$input_number = «444»; // Answer 1
$input_number = «44 «; // Answer 2
$input_number = «4 4»; // Answer 2
$input_number = «4e4»; // Answer 2
$input_number = «e44»; // Answer 2
$input_number = «e4e»; // Answer 2
$input_number = «abc»; // Answer 2
*/
$input_number = «444» ;
The solution is pretty simple and no subroutines or fancy operations are necessary to make the ‘is_numeric’ function usable for form entry checks:
Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.
Just use the ‘trim’ function before ‘is_numeric’.
Two simple functions using is_numeric:
?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
«italy»: odd? FALSE
null: odd? FALSE
1: even? FALSE
0: even? TRUE
6: even? TRUE
«italy»: even? FALSE
null: even? FALSE
Here’s a function to determine if a variable represents a whole number:
just simple stuff.
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:
function new_is_unsigned_float($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^(7)+([\.|,](3)*)?$»,$val);
>
function new_is_unsigned_integer($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^(1)+$»,$val);
>
function new_is_signed_float($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^-?(3)+([\.|,](8)*)?$»,$val);
>
function new_is_signed_integer($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^-?(8)+$»,$val);
>
It returns 1 if okay and returns nothing «» if it’s bad number formating.
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function). Note that this doesn’t properly handle decimals.
Also, increasing the range above the condition statements increases efficiency. That’s almost 20% of the numbers between 0 and 100 that get to end early.
Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world’s way:
(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
Here’s an even simpler pair of functions for finding out if a number is odd or even:
if(IS_ODD($myNumber))
echo(«number is odd\n»);
else
echo(«number is NOT odd\n»);
if(IS_even($myNumber))
echo(«number is even\n»);
else
echo(«number is NOT even\n»);
Results:
number is odd
number is NOT even
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:
The output in this case would be ‘654.45’.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.
ie : two scripts test.php:
Note that this function is not appropriate to check if «is_numeric» for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.
However, this behaviour is platform-specific.
In such a case, it is suitable to use regular expressions:
I find it a little weird that people are having issues with ordinal numbers, it’s pretty easy..
Notes are in the commenting, check out the example outputs.
var_dump ( ordinal ( 5 ));
ordinal(‘-1’); returns false because ctype_digit hates anything that
isn’t strictly 0 through 9 and ‘-‘ trips it to false.
ordinal(‘asdf’); returns false for the exact same reason.
ordinal(); returns false because it’s blank.
signed integers on a 32-bit system (and the same issue on a 64-bit
system using 0x7FFFFFFFFFFFFFFF because of two’s compliment,
anything higher will become a negative number):
ordinal(0x7FFFFFFF ); returns 2147483647th (which is correct)
ordinal(0x7FFFFFFF+1); returns false.
*/