views:

266

answers:

6

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.

+2  A: 

there is a native function called intval(). Is that's what you're looking for?

iNPUTmice
That just returns the value of the input as an integer, it doesn't do any validation. Objects that are not integers will return 0.
davethegr8
+6  A: 

You could try ctype_digit or is_numeric

Bart S.
Thanks I'll try to combine ctype_digit or is_numeric with something else. Not exactly what I was looking for, but close enough.
Mikk
+1  A: 

it won't accept "0003" cause it's not 'clear' integer. Integer can't start with zero but it can be negative (notice that you remove '-' with your function). As said before me, use ctype_digit or is_numeric

confiq
Actually '-' stays (because $validate get's value substr($int,1) or just $int, and (int)$int is returned), my bad - probably comments in my code weren't clear enough.
Mikk
A: 

You could use intval as Jacob suggests.

However, if you want a Locale aware int validation class, then I suggest using the Zend Framework's Zend_Validate_Int validator.

Usage

<?php
$v = new Zend_Validate_Int();
if ($v->isValid($myVal)) {
    // yay
} else {
    // fail
}

Note that because of the pick-and-choose structure of the Zend Framework, you don't need to use this for your entire application. The Validators have minimal dependencies on Zend_Locale, for locale aware validation, and Zend_Registry.

hobodave
A: 

Quick and dirty way, won't handle '0003' as far as I know.

function parseInt($in) {
    return ($in == intval($in) ? $in : false);
}
davethegr8
A: 

You could also use PEAR's Validate package; http://pear.php.net/manual/en/package.validate.validate.number.php

Various option are:

  1. decimal (mixed) - Decimal chars or false when decimal not allowed. For example ",." to allow both "." and ",".
  2. dec_prec (int) - Number of allowed decimals.
  3. min (float) - Minimum value.
  4. max (float) - Maximum value.
kguest