php проверить что число
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(«^(1)+([\.|,](4)*)?$»,$val);
>
function new_is_unsigned_integer($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^(9)+$»,$val);
>
function new_is_signed_float($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^-?(1)+([\.|,](3)*)?$»,$val);
>
function new_is_signed_integer($val) <
$val=str_replace(» «,»»,trim($val));
return eregi(«^-?(2)+$»,$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.
*/
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.
Проверка, является ли переменная целым числом в 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 для строкового эквивалента отрицательного целого числа, поэтому не используйте этот метод, если вы не уверены, что ваш вход никогда не будет содержать отрицательное число в строке или целочисленная форма, и если это так, ваш процесс не будет нарушать это поведение.
код, используемый для получения вывода выше:
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 есть задачи, которые встречаются чаще остальных или просто как-то выделяются из общего множества. В этой статье поговорим о некоторых из них.
Тут собрана лишь малая часть, и наверное это не последняя статья на тему несложных популярных задачек в PHP. Кроме того, я планирую дополнять эту статью.
Короткая запись операторов присваивания
Время выполнения PHP скрипта
Округление дробных чисел
Округление до целых
Чтобы округлить число в php существует несколько функций:
Округление до дробных
Округление последнего числа происходит как в математики: если следующее больше или равно 5 то в большую сторону, в остальных случаях в меньшую.
Целая часть и остаток от деления чисел
Чтобы получить остаток от деления можно воспользоваться оператором % :
Числа кратные к N или каждый N-ый блок в цикле
Нужно разделить число на число и если остатка нет, то первое число делиться нацело на второе, а значит кратное.
Где применить эту кратность?
Допустим, есть цикл записей и нужно к каждому третьему блоку добавить отдельный css класс. Тут-то кратность нам и поможет.
Форматирование чисел (денег) в PHP
Форматирует число с разделением групп.
number(обязательный)
Число, которое нужно отформатировать.
decimals
Сколько знаков после запятой показывать.
dec_point
Разделитель для дробной части.
Для форматирования с учетом языка сайта в WordPress есть специальная функция number_format_i18n()
Для вывода денежных величин используйте похожую функцию money_format()
Как получить ключи или значения ассоциативного PHP массива
Это может пригодится когда нужно сделать поиск по ключам массива. В PHP такой встроенной функции нет.
Создаем массив из диапазона чисел или букв
Как получить максимальное или минимальное число из массива в PHP
Также можно передать массив из чисел, тогда мин. или макс. число будет выбрано из значений массива.
Как получить часть строки (подстроку)
Однако нужно знать, что скорость их работы в разы ниже: substr() работает с одинаковой скоростью для строки любой длинны. А вот mb_substr() и iconv_substr() работают тем медленнее чем длине строка в них указывается. В среднем они в 5-10 раз медленнее, однако альтернатив нет, если нужно обработать кириллицу, придется использовать их.
Количество символов в строке
Как посчитать сколько раз встречается одна строка в другой
Удаление символов внутри строки
Сделать это можно многими способами, но самый простой это функция str_replace() :
Удаление символов на концах строки
Также, не все знают что есть аналогичные функции:
Удаление пустых символов на концах строки
Удаление указанных символов в начале и конце строки
Как перевернуть строку в PHP
День недели и месяц по-русски на PHP
Месяц по-русски
День недели
Есть что добавить? Милости прошу в комментарии.