Best way to check for positive integer (PHP)?
the difference between your two code snippets is that is_numeric($i)
also returns true if $i is a numeric string, but is_int($i)
only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).
See these references for more information:
php is_numeric function
php is_int function
Shortest way to check if a variable contains positive integer using PHP?
Something like this should work. Cast the value to an integer and compare it with its original form (As we use ==
rather than ===
PHP ignores the type when checking equality). Then as we know it is an integer we test that it is > 0. (Depending on your definition of positive you may want >= 0
)
$num = "20";
if ( (int)$num == $num && (int)$num > 0 )
Check if variable is a number and positive integer in PHP?
To check if a string input is a positive integer, i always use the function ctype_digit. This is much easier to understand and faster than a regular expression.
if (isset($_GET['p']) && ctype_digit($_GET['p']))
{
// the get input contains a positive number and is safe
}
PHP - Check for positive / negative numeric strings
Your problem is because: (int)"+2.1" == 2
and 2 != "+2.1"
. For ALL numbers, if it is < 0
it is negative and if it is > 0
it is positive. If it is == 0
, then it is obviously 0
which is unsigned.
function check_numb($Degree){
if ( $Degree > 0 ) {
return 'Positive';
} elseif( $Degree < 0 ) {
return 'Negative';
}
}
How to check a query string is a positive integer in PHP
OK, if you need int values use ctype_digit()
if (! (ctype_digit($url_segments['cid']) and ctype_digit($url_segments['bid']))
and (ctype_digit($url_segments['cid'])<=0 or ctype_digit($url_segments['bid'])<=0) ) {
}
php How to check if an array of numbers are all positive
Could you just use min to get the desired result?
return min($array) >= 0
PHP: Best way to check if input is a valid number?
ctype_digit
was built precisely for this purpose.
How can I find whether 0 is integer or not in php
i'm recommendation to use you with is_numeric
if (is_numeric(0)) { echo "Yes"; } else { echo "No"; }
// OUTPUT = YES
DEMO
Related Topics
How to Redirect to Different Url Based on Roles in Symfony 2
How to Measure the Strength of a Password
Phpmailer - How to Remove Recipients
How to Extract or Uncompress Gzip File Using PHP
Mysql_Connect VS MySQL_Pconnect
Updating Column So That It Contains the Row Position
Checking If a String Contains an Integer
Store HTML Entities in Database? or Convert When Retrieved
Curl File Uploads Not Working Anymore After Upgrade from PHP 5.5 to 5.6
Remove Zero Values from a PHP Array
How to Strip Out the Domain Name from a Url in PHP
How to Check If a File Exists on a Remote Server Using PHP
How to Eliminate PHP5 Strict Standards Errors
How to Insert into MySQL Using a Prepared Statement with PHP