Check a variable is an integer

Hi,

I’d like to check if a variable is a number and only a number.

Can anyone point me in the right and simple direction?

Thank you.

is_int() if it is an integer.

is_numeric() if it is an integer or a number as a string (i.e. 51 or ‘51’)

compare ctype_digit() to is_numeric() and pick the most suitable.

Many thanks Raffles :slight_smile:

I’ve been getting strange requests in my access logs where it should be retrieving integers.
Things like item.php?id=-8+order+by+23

I will now make the change, which should hopefully fix things :slight_smile:

Thank you.

Many thanks malibu too.
In the end, I opted for is_numeric.

Thank you once more for all your help.

Alternatively we can use regular expression:

if(preg_match('/^[0-9]+$/', $integer)){
//passed the validation
}

Many thanks for the replies.

Just a quick off-topic.

What would be a good regular expression to validate the following is true:

CDS-FH-0188

So there’s letters and numbers, and hyphens. But I don’t want any other characters, nor do I want the hyphens as bookends.

Is there a reg exp I can use for this?

You can try this:

preg_match('/([a-zA-Z]+)-([a-zA-Z]+)-([0-9]+)/i', $string);

Aaaah genius.

So in an if statement, something like


$string = "-CDS-FH-0018";

if (preg_match('/([a-zA-Z]+)-([a-zA-Z]+)-([0-9]+)/i', $string)) {

// should fail

} else {

// should pass

}

Is that the right idea?

Thanks again.

Sorry my mistake:
corrected:

preg_match('/^([a-zA-Z]+)-([a-zA-Z]+)-([0-9]+)$/i', $string)

note the changes.

Now try this:

$string = "-CDS-FH-0018";
if(preg_match('/^([a-zA-Z]+)-([a-zA-Z]+)-([0-9]+)$/i', $string)){
echo 'Passed';
}

I’d probably go for something a little more explicit.


<?php
if(1 === preg_match('~^[A-Z]{3}-[A-Z]{2}-[0-9]{4}$~', 'CDS-FH-0188')){
    #valid
}
?>

Brilliant Anthony, that looks great to me :slight_smile:

Always remember to include the D flag unless you’re ok with the end of the string being a newline.


var_dump(preg_match('#^a$#', "a\
"));
var_dump(preg_match('#^a$#D', "a\
"));