PHP validating integers

Posted by Mikk on Stack Overflow See other posts from Stack Overflow or by Mikk
Published on 2010-04-04T15:53:01Z Indexed on 2010/04/04 16:03 UTC
Read the original article Hit count: 214

Filed under:
|
|

Hi,

I was wondering, what would be the best way to validate an integer. I'd like this to work with strings as well, so I could to something like

(string)+00003 -> (int)3 (valid)

(string)-027 -> (int)-27 (valid)

(int)33 -> (int)33 (valid)

(string)'33a' -> (FALSE) (invalid)

That is what i've go so far:

function parseInt($int){
    //If $int already is integer, return it
    if(is_int($int)){return $int;}
//If not, convert it to string
$int=(string)$int;
//If we have '+' or '-' at the beginning of the string, remove them
$validate = ($int[0] === '-' || $int[0] === '+')?substr($int, 1):$int;
//If $validate matches pattern 0-9 convert $int to integer and return it
//otherwise return false
return preg_match('/^[0-9]+$/', $validate)?(int)$int:FALSE;
}

As far as I tested, this function works, but it looks like a clumsy workaround.

Is there any better way to write this kind of function. I've also tried

filter_var($foo, FILTER_VALIDATE_INT);

but it won't accept values like '0003', '-0' etc.

© Stack Overflow or respective owner

Related posts about php

Related posts about integer