Take the 2-minute tour ×

I've a problem. I'm scrapping a txt file and extracting an ID. The problem is that the data is not consistent and I have to evaluate the data.

Here is some code:

$a = "34";
$b = " 45";
$c = "ddd556z";

if (  ) {

    echo "INTEGER";
} else{ 

    echo "STRING";

I need test if the values $a, $b or $c are Integers. What is the best way of doing this? I have tested to "trim" and the use "is_int" but is not working as expected.

Can someone give me some clues?

share|improve this question
as your data are all strings in this example you will show false when using is_int($a) (or $b or $c) What results are you expecting? $a and $b to be true? Then either cast to an int or use is_numeric() however note that floats, doubles and numbers using scientific notation will also show as true using is_numeric(). php.net/manual/en/function.is-numeric.php –  billythekid Jun 13 '11 at 11:10
add comment

3 Answers

up vote 8 down vote accepted

The example below will work even if your "int" is a string $a = "number";



preg_match( '/^-?[0-9]+$/' , $var )  // negative number © Piskvor


intval($var) == $var

or (same as last)

(int) $var == $var
share|improve this answer
-1 is not an integer? –  Piskvor Jun 13 '11 at 11:09
Only the example with preg will not validate -1. All other will. –  llnk Jun 13 '11 at 11:11
@yes123: Integers. Note the part about negative numbers - the OP didn't specify "positive integers", did he? ( /^-?[0-9]+$/ would work) –  Piskvor Jun 13 '11 at 11:15
@piskvor: I have wrote 4 example. Only the preg doens't match the negative number. do you think it is enough to give a -1? ... anyway I have added your solution in my answer. +1 to you –  llnk Jun 13 '11 at 11:17
@yes123: "Part of my answer is wrong, so what?" Well, that's definitely worthy of the highest negative integer. –  Piskvor Jun 13 '11 at 11:19
show 1 more comment


$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";

// will output
//The string 1820.20 does not consist of all digits.
//The string 10002 consists of all digits.
//The string wsl!12 does not consist of all digits.
share|improve this answer
add comment
$a = 34;
if (is_int($a)) {
    echo "is integer";
} else {
    echo "is not an integer";

will not validate as int ;)

share|improve this answer
can't work because he has $a = "34"; –  llnk Jun 13 '11 at 11:11
yeah, I have mentioned it also.. –  Vamsi Jun 13 '11 at 11:13
add comment

Your Answer


