- Работа с числами в PHP
- Проверка переменных
- Является ли переменная числом
- Целое или число с плавающей точкой
- Положительное или отрицательное
- Чётное или нечётное
- Привидение к типу
- Преобразование в целое число
- Преобразование в число с плавающей точкой
- Округление
- Округление до целого числа в меньшую сторону:
- Округление до целого числа в большую сторону:
- Ведущие нули
- Добавить ведущие нули:
- Удалить ведущие нули:
- Абсолютное значение
- Сделать число отрицательным:
- Инкремент и декремент
- Минимальное значение
- is_numeric
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 8 notes
- is_numeric
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- PHP is_numeric() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Работа с числами в PHP
Сборник математических функций PHP и примеры их использования.
Проверка переменных
Является ли переменная числом
is_numeric($value) – проверяет, является ли значение или переменная числом или строкой, содержащей число.
is_numeric(1); // true is_numeric(0.1); // true is_numeric(-1); // true is_numeric(-0.1); // true is_numeric('1'); // true is_numeric('1abc'); // false is_numeric('abc'); // false
ctype_digit($value) – проверяет, являются ли все символы в строке цифрами.
ctype_digit('123'); // true ctype_digit('123.10'); // false ctype_digit('abc'); // false ctype_digit('1abc'); // false ctype_digit('abc1'); // false
is_int($value) – проверяет, является ли значение целым числом.
is_int(1); // true is_int(0.1); // false is_int(-1); // true is_int(-0.1); // false is_int('1'); // false is_int('1abc'); // false is_int('abc'); // false
is_float($value) – проверяет, является ли значение числом с плавающей точкой.
is_float(1); // false is_float(0.1); // true is_float(-1); // false is_float(-0.1); // true is_float('1'); // false is_float('1abc'); // false is_float('abc'); // false
Целое или число с плавающей точкой
Следующий пример определяет является ли число целым или с плавающей точкой, при этом не проверяет его отрицательность.
$value = 1; if (is_int($value)) < echo 'Целое число'; >elseif (is_float($value)) < echo 'Число с плавающей точкой'; >else
Положительное или отрицательное
$value = 1; if ($value == abs($value)) < echo 'Число положительное'; >if ($value != abs($value))
Чётное или нечётное
$value = 100; if (($value % 2) == 0) < echo 'Число чётное'; >if (($value % 2) != 0)
Привидение к типу
Преобразование в целое число
(int) 1; // 1 (int) 0.1; // 0 (int) -1; // -1 (int) -0.1; // 0 (int) '1'; // 1 (int) 'abc'; // 0 (int) '1abc'; // 1 (int) 'abc1'; // 0
В место (int) можно использовать (intiger) . Тоже самое делает функция intval() :
intval(1); // 1 intval(0.1); // 0 intval(-1); // -1 intval(-0.1); // 0 intval('1'); // 1 intval('abc'); // 0 intval('1abc'); // 1 intval('abc1'); // 0
Преобразование в число с плавающей точкой
(float) 1; // 1 (float) 0.1; // 0.1 (float) -1; // -1 (float) -0.1; // -0.1 (float) '1'; // 1 (float) 'abc'; // 0 (float) '1abc'; // 1 (float) 'abc1'; // 0
В место (float) можно использовать (double) или (real) и тоже самое делает функция floatval() .
floatval(1); // 1 floatval(0.1); // 0.1 floatval(-1); // -1 floatval(-0.1); // -0.1 floatval('1'); // 1 floatval('abc'); // 0 floatval('1abc'); // 1 floatval('abc1'); // 0
Округление
Функция round($value, $precision) округляет значение до указанных цифр после запятой.
echo round(100001.123456, 2); // 100001.12
Функция может окрукруглять значение целой части (числа перед запятой), для этого нужно указать отрицательное значение во втором аргументе.
Округление до целого числа в меньшую сторону:
echo floor(100.4); // 100 echo floor(100.9); // 100
Округление до целого числа в большую сторону:
echo ceil(100.4); // 101 echo ceil(100.1); // 101
Ведущие нули
Добавить ведущие нули:
echo sprintf("%06d", 100); // 000100 echo sprintf("%010d", 100); // 0000000100
Удалить ведущие нули:
echo intval('0000000100'); // 100 // Или с помощью ltrim echo ltrim('0000000100', '0'); // 100
Абсолютное значение
Функция abs($value) – возвращает абсолютное значение (модуль числа), т.е. из отрицательного делает положительное.
echo abs(100); // 100 echo abs(-100); // 100 echo abs(1.5); // 1.5 echo abs(-1.5); // 1.5
Сделать число отрицательным:
$value = 10; $value = -abs($value); echo $value; // -10
Инкремент и декремент
Инкремент – увеличение значения на единицу, бывает постфиксный и префиксный.
// Постфиксный инкремент $value = 10; echo $value++; // 10 echo $value; // 11 // Префиксный инкремент $value = 10; echo ++$value; // 11 echo $value; // 11
Декремент уменьшает значение на единицу.
// Постфиксный декремент $value = 10; echo $value--; // 10 echo $value; // 9 // Префиксный декремент $value = 10; echo --$value; // 9 echo $value; // 9
Минимальное значение
is_numeric
Determines if the given variable is a number or a numeric string.
Parameters
The variable being evaluated.
Return Values
Returns true if value is a number or a numeric string, false otherwise.
Changelog
Version | Description |
---|---|
8.0.0 | Numeric strings ending with whitespace ( «42 » ) will now return true . Previously, false was returned instead. |
Examples
Example #1 is_numeric() examples
$tests = array(
«42» ,
1337 ,
0x539 ,
02471 ,
0b10100111001 ,
1337e0 ,
«0x539» ,
«02471» ,
«0b10100111001» ,
«1337e0» ,
«not numeric» ,
array(),
9.1 ,
null ,
» ,
);
?php
foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » is numeric» , PHP_EOL ;
> else echo var_export ( $element , true ) . » is NOT numeric» , PHP_EOL ;
>
>
?>
The above example will output:
'42' is numeric 1337 is numeric 1337 is numeric 1337 is numeric 1337 is numeric 1337.0 is numeric '0x539' is NOT numeric '02471' is numeric '0b10100111001' is NOT numeric '1337e0' is numeric 'not numeric' is NOT numeric array ( ) is NOT numeric 9.1 is numeric NULL is NOT numeric '' is NOT numeric
Example #2 is_numeric() with whitespace
$tests = [
» 42″ ,
«42 » ,
«\u9001» , // non-breaking space
«9001\u» , // non-breaking space
];
?php
foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » is numeric» , PHP_EOL ;
> else echo var_export ( $element , true ) . » is NOT numeric» , PHP_EOL ;
>
>
?>
Output of the above example in PHP 8:
' 42' is numeric '42 ' is numeric ' 9001' is NOT numeric '9001 ' is NOT numeric
Output of the above example in PHP 7:
' 42' is numeric '42 ' is NOT numeric ' 9001' is NOT numeric '9001 ' is NOT numeric
See Also
- Numeric strings
- ctype_digit() — Check for numeric character(s)
- is_bool() — Finds out whether a variable is a boolean
- is_null() — Finds whether a variable is null
- is_float() — Finds whether the type of a variable is float
- is_int() — Find whether the type of a variable is integer
- is_string() — Find whether the type of a variable is string
- is_object() — Finds whether a variable is an object
- is_array() — Finds whether a variable is an array
- filter_var() — Filters a variable with a specified filter
User Contributed Notes 8 notes
Note that the function accepts extremely big numbers and correctly evaluates them.
$v = is_numeric ( ‘58635272821786587286382824657568871098287278276543219876543’ ) ? true : false ;
var_dump ( $v );
?>
The above script will output:
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
Apparently NAN (Not A Number) is a number for the sake of is_numeric().
echo «is » ;
if (! is_numeric ( NAN ))
echo «not » ;
echo «a number» ;
?>
Outputs «is a number». So something that is NOT a number (by defintion) is a number.
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
is incorrect for PHP8, it’s numeric.
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:
function is_numeric_big($s=0) return preg_match(‘/^-?\d+$/’, $s);
>
Note that is_numeric() will evaluate to false for number strings using decimal commas.
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren’t grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim’s regexen are slightly suboptimal at one point having an unescaped ‘.’ operator, and the whole thing could easily be combined into a single regex (speed and all).
$eng_or_world = preg_match
( ‘/^[+-]?’ . // start marker and sign prefix
‘((((3+)|(1(,7)+)))?(\\.9)?(6*)|’ . // american
‘(((9+)|(3(\\.7)+)))?(,5)?(7*))’ . // world
‘(e4+)?’ . // exponent
‘$/’ , // end marker
$str ) == 1 ;
?>
i’m sure this still isn’t optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
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
);
?php
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() — Определяет, является ли переменная массивом
PHP is_numeric() Function
Check whether a variable is a number or a numeric string, or not:
$b = 0;
echo «b is » . is_numeric($b) . «
«;
$c = 32.5;
echo «c is » . is_numeric($c) . «
«;
$d = «32»;
echo «d is » . is_numeric($d) . «
«;
$e = true;
echo «e is » . is_numeric($e) . «
«;
$f = null;
echo «f is » . is_numeric($f) . «
«;
?>
Definition and Usage
The is_numeric() function checks whether a variable is a number or a numeric string.
This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.
Syntax
Parameter Values
Technical Details
Return Value: | TRUE if variable is a number or a numeric string, FALSE otherwise |
---|---|
Return Type: | Boolean |
PHP Version: | 4.0+ |
❮ PHP Variable Handling Reference
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.