How does PHP determine if a string is an integer
Two methods: 1. Use intval() to convert the string to an integer value, and then use the “==” operator to determine whether the integer value is equal to the original string. The syntax “intval($STR)==$STR”, equality is an integer. 2. Use is_numeric() and strpos() to determine whether the string is a numeric string that does not contain a decimal point. is_numeric($str)||strpos($str,”.”)! ==false “, returns false is an integer, and vice versa.
There are two ways PHP can determine if a string is an integer
Method 1: Use intval() and the “==” operator
Use intval() to convert a string to an integer value
Use the “==” operator to determine whether the integer value is equal to the original string
<?php
header("Content-type:text/html; charset=utf-8");
function f($str){
$result = intval($str);
if($result==$str){
Echo "$STR string is an integer
";
}
else{
Echo "$STR string is not an integer
";
}
}
f("a678");
f("678");
F (" 3.14 ");
? >
Method 2: Use the is_numeric() and strpos() functions
Use the is_numeric() function to determine whether it is a number or string of numbers (integers and floating-point numbers).
Use strpos() to determine if a number contains a decimal point — excluding floating point numbers
You just need to determine if the string is a numeric string that does not contain a decimal point
<?php
header("Content-type:text/html; charset=utf-8");
function f($str){
if(! is_numeric($str)||strpos($str,".")! ==false){
Echo "$STR string is not an integer
";
}else{
Echo "$STR string is an integer
";
}
}
f("a678");
F (" 3.14 ");
f("67854");
? >
Description:
Intval () function
The intval() function is used to get the integer value of a variable.
The intval() function returns the INTEGER value of the variable var by using the specified base conversion (default is decimal). Intval () cannot be used on object, otherwise an E_NOTICE error is generated and 1 is returned.