note 35820 added to function.is-int
| From: | lclkk at urbanvagabond dot net | Date: | Mon, 15 Sep 2003 23:24:49 +0000 |
| Subject: | note 35820 added to function.is-int | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-56548@lists.php.net to get a copy of this message | ||
I think the function below is a robust test for integers working on all datatypes. It works by first
checking that a number can be evaluated numerically, and then secondly that the integer evaluation
matches the original number.
Test cases are included.
<?
function myIsInt ($x) {
return (is_numeric($x) ? intval($x) == $x : false);
}
function Test($x) {
echo "$x is " . ( myIsInt($x) ? ('an integer. The integer value is ' .
intval($x)) : 'not an integer.');
echo "\n";
}
echo "These should be integers...\n";
Test(1);
Test(5);
Test(10);
Test(10.0);
Test(20.0);
Test(-20.0);
Test(0+4+4.5+4.5);
Test("10.0");
Test("+14");
Test("-15");
Test("0");
echo "\nThese should not be integers...\n";
Test(true); // watch out, this displays as '1'
Test(false);
Test("moose");
Test("3.5");
Test("-214235.5");
Test(""); // empty string
Test(array(1,2,3));
Test(dir('.')); // object
Test(null);
?>
----
Manual Page -- http://www.php.net/manual/en/function.is-int.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35820
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35820&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35820&report=yes