Php how to check number

How to Check if a String is a Number in PHP: Tips and Techniques

Learn how to check if a string is a number in PHP using built-in functions like is_numeric(), is_int(), and is_float(). Convert a string to a number using number_format() and intval(). Best practices and common issues are also discussed.

  • Using is_numeric()
  • Other Related Functions
  • Using Regular Expressions
  • Converting a String to a Number
  • Best Practices and Common Issues
  • Other helpful code examples for checking if a string is a number in PHP
  • Conclusion
  • How do you check if a string starts with a number in PHP?
  • How do you check if a variable is an integer in PHP?
  • How do you check if a number is integer or float in PHP?
  • How to convert string to number in PHP?

PHP is a widely-used programming language, especially for web development. Checking if a string is a number is a common task when working with PHP. In this article, we will explore the built-in function is_numeric() and other related functions and techniques available to check for numeric values in PHP. We will also discuss best practices and common issues when working with strings and numbers in PHP.

Читайте также:  Пояснение работы парсера

Using is_numeric()

The is_numeric() function takes a string as an argument and returns true if the string is numeric, otherwise false. This function also returns true for numeric strings. Here’s an example of using is_numeric() to check for numeric values in PHP:

$number = "123"; if (is_numeric($number)) < echo "The string is a number"; >else

Output: The string is a number.

In addition to is_numeric(), PHP provides other related functions to check for numeric values.

is_int()

The is_int() function only returns true if the variable is of type integer, not for numeric strings. Here’s an example of using is_int() to check for integer values in PHP:

$number = 123; if (is_int($number)) < echo "The variable is an integer"; >else

Output: The variable is an integer.

is_float()

The is_float() function checks whether a variable is of type float or not. Here’s an example of using is_float() to check for float values in PHP:

$number = 1.23; if (is_float($number)) < echo "The variable is a float"; >else

Output: The variable is a float.

ctype_digit()

The ctype_digit() function checks for numeric characters only. Here’s an example of using ctype_digit() to check for numeric characters in PHP:

$number = "123"; if (ctype_digit($number)) < echo "The string contains only numeric characters"; >else

Output: The string contains only numeric characters.

ctype_alnum()

The ctype_alnum() function checks for alphanumeric characters only. Here’s an example of using ctype_alnum() to check for alphanumeric characters in PHP:

$string = "abc123"; if (ctype_alnum($string)) < echo "The string contains only alphanumeric characters"; >else

Output: The string contains only alphanumeric characters.

is_string()

The is_string() function checks whether a variable is of type string or not. Here’s an example of using is_string() to check for string values in PHP:

$string = "abc123"; if (is_string($string)) < echo "The variable is a string"; >else

Output: The variable is a string.

Using Regular Expressions

Regular expressions can be used with preg_match() to check if a string contains any numbers or a specific word. Here’s an example of using regular expressions for string manipulation in PHP:

$string = "The quick brown fox jumps over the lazy dog"; if (preg_match("/\d/", $string)) < echo "The string contains a number"; >else

Output: The string does not contain a number.

Converting a String to a Number

Sometimes it’s necessary to convert a string to a number in php. PHP provides two functions for this purpose: number_format() and intval().

number_format()

The number_format() function can be used to convert a string into a number. Here’s an example of using number_format() to convert a string to a number in PHP:

$string = "123.45"; $number = number_format($string, 2); echo $number; 

intval()

The intval() function can be used to convert a string to an integer. Here’s an example of using intval() to convert a string to an integer in PHP:

$string = "123"; $number = intval($string); echo $number; 

Best Practices and Common Issues

Using proper syntax and error handling is important when working with strings and numbers in PHP. Understanding the differences between integer, float, and string types is important when working with numbers in PHP. Using appropriate data types and variable naming conventions can improve code readability and maintainability. Common issues when working with strings and numbers in PHP include type conversion errors and unintended string manipulation. best practices for php development include using secure coding practices and keeping code up to date with the latest PHP versions.

Other helpful code examples for checking if a string is a number in PHP

In php, check if string is number or not php code example

$var_num = "1"; $var_str = "Hello World";var_dump( is_numeric($var_num), is_numeric($var_str) );/* Output - bool(true) bool(false) */

In php, php is numeric code example

//is_numeric — Finds whether a variable is a number or a numeric string is_numeric ( $variable ); // returns true or false
## CHECK IF INPUT IS NUMBER ONLY $number = "12345"; is_numeric($number); ## RETURNS TRUE IF NUMBER ONLY, ELSE FALSE

In php, php check if string or number code example

In php, php check string is int code example

In php, php check if string or number code example

Conclusion

checking if a string is a number in php is a common task that can be accomplished using the built-in function is_numeric(). There are also other related functions and techniques available to check for numeric values in PHP. Converting a string to a number can be done using functions such as number_format() and intval(). Understanding best practices and common issues when working with strings and numbers in PHP is important for proper coding and maintenance.

Источник

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

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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.

Источник

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 ,
» ,
);

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
];

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
‘((((8+)|(3(,1)+)))?(\\.1)?(8*)|’ . // american
‘(((4+)|(3(\\.8)+)))?(,2)?(1*))’ . // world
‘(e5+)?’ . // 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.

Источник

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