FRIHOSTFORUMSFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

Integer

 


Afaceinthematrix
Is there anyway, or function, that can tell if a returned number is an integer in PHP?
hexkid
is_ int()
chris20
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
hexkid
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"; }
Aredon
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
?>
yjwong
To check whether an integer is positive or negative, here's another easy way:
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.
hexkid
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"; }
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.