php проверить что число
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()
Результат выполнения данного примера:
Пример #2 Пример использования is_numeric() с пробелом
Результат выполнения данного примера в PHP 8:
Результат выполнения данного примера в PHP 7:
Список изменений
Смотрите также
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
?>
/* 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» ;
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.
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
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:
ctype_digit
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
ctype_digit — Проверяет наличие цифровых символов в строке
Описание
Проверяет, являются ли все символы в строке text цифровыми.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования ctype_digit()
Результат выполнения данного примера:
Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел
Смотрите также
User Contributed Notes 14 notes
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.
The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.
(Note: the PHP type must be an int; if you pass strings it works as expected)
PHP проверка на число
Как в php проверить является ли переменная целым положительным число. Именно целым (дробное не допускается), т.е. функция is_numeric не подходит. ( is_int тоже не подходит )
14 ответов 14
P.S: Существует бесконечное кол-во способов решения вашего туманно сформулированного вопроса
Уже предложена куча вариантов, но я бы наверное сделал так
как вариант проверь сначала is_numeric, а потом проверь что в строке отсутствуют знаки ‘+’ и ‘.’ и ‘,’
Мне нравится такое решение, всегда использую:
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.12.20.41044
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Проверка, является ли переменная целым числом в 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 для строкового эквивалента отрицательного целого числа, поэтому не используйте этот метод, если вы не уверены, что ваш вход никогда не будет содержать отрицательное число в строке или целочисленная форма, и если это так, ваш процесс не будет нарушать это поведение.
код, используемый для получения вывода выше: