Is there anyway, or function, that can tell if a returned number is an integer in PHP?
Integer
is_int doesnt differentiate between positive and negative, as it shouldn't of course since an integer can also be negative, but for my purposes of number checking, i generally need to check if it is a positive integer, so i just thought id throw this up here for you if this is also the case for you
use the following regular expression for positive ints ^[0-9]
so use it like this... preg_match("/^[0-9]/", $input)
where $input is ur string to check
use the following regular expression for positive ints ^[0-9]
so use it like this... preg_match("/^[0-9]/", $input)
where $input is ur string to check
| chris20 wrote: |
| use the following regular expression for positive ints ^[0-9]
so use it like this... preg_match("/^[0-9]/", $input) where $input is ur string to check |
| Code: |
| $input = '-42'; if (preg_match("/^[0-9]/", $input)) { echo "Oops<br>\n"; }
$input = '4.2'; if (preg_match("/^[0-9]/", $input)) { echo "Oops<br>\n"; } $input = '4-2'; if (preg_match("/^[0-9]/", $input)) { echo "Oops<br>\n"; } $input = '4+2'; if (preg_match("/^[0-9]/", $input)) { echo "Oops<br>\n"; } $input = '4w'; if (preg_match("/^[0-9]/", $input)) { echo "Oops<br>\n"; } |
| Code: |
| $input = '-42'; if (is_int($input) && $input >= 0) { echo "Oops<br>\n"; }
$input = '4.2'; if (is_int($input) && $input >= 0) { echo "Oops<br>\n"; } $input = '4-2'; if (is_int($input) && $input >= 0) { echo "Oops<br>\n"; } $input = '4+2'; if (is_int($input) && $input >= 0) { echo "Oops<br>\n"; } $input = '4w'; if (is_int($input) && $input >= 0) { echo "Oops<br>\n"; } |
is_int will not treat string-numbers as numbers. Make sure to run string-numbers through (int) first.
| Code: |
|
<?php echo is_int("7")?"true":"false";//echos false echo "\n<br>"; echo is_int( (int)"7" )?"true":"false";//echos true ?> |
To check whether an integer is positive or negative, here's another easy way:
To check whether the number is a number (which includes "integers" in strings), use the is_numeric() function.
| Code: |
|
$int1 = -1; if(abs($int1) == $int1){ echo "This is a positive integer!"; } else { echo "This is a negative integer!"; } |
To check whether the number is a number (which includes "integers" in strings), use the is_numeric() function.
| chris20 wrote: |
| so use it like this... preg_match("/^[0-9]/", $input) |
Try preg_match('/^[0-9]+$/', $input) instead
| Code: |
| $input = '-42'; if (preg_match("/^[0-9]+\$/", $input)) { echo "Oops<br>\n"; }
$input = '4.2'; if (preg_match("/^[0-9]+\$/", $input)) { echo "Oops<br>\n"; } $input = '4-2'; if (preg_match("/^[0-9]+\$/", $input)) { echo "Oops<br>\n"; } $input = '4+2'; if (preg_match("/^[0-9]+\$/", $input)) { echo "Oops<br>\n"; } $input = '4w'; if (preg_match("/^[0-9]+\$/", $input)) { echo "Oops<br>\n"; } |
