It makes me feel like a right noob asking this, but is there any built-in php function that will tell you whether a variable represents an integer, or a string integer eg 2 or “2” but not 2.4 or “2.4”.
is_int() will be false if it is a string.
is_numeric will allow decimal places and ± signs.
I usually just use my own function, but am I missing something built in?
Hmm ok i had to go re-write this whole thing because that was annoying me. This code is tested and works.
function isInt($int){
// boolean true or false if $int is 0
$zero = false;
// compares the argument to quoted 0
if(str_replace(array("'" , '"') , '"' , $int) == "0"){
$zero = true;
}
// convert the argument to an int no matter what.
$int = (int) $int;
// is the value a zero and the argument is a 0
if($int == 0 and $zero == true){
return true;
}
// is the value a zero and the argument not a 0
elseif($int == 0 and $zero == false){
return false;
}
// is it not a 0 and an int
elseif($int !== 0 and is_int($int)){
return true;
}
// false for all else
return false;
}
hessodreamy, could you clarify exactly what values you want to allow? You briefly mentioned signs, in relation to is_numeric(); do you want to return false if any sign is encountered, or only for negative? What range of values do you want to accept? The range of the integer type varies between signed/unsigned and 32/64-bit machines. Since you’re accepting strings, will your integers be bound by any of these or accept an arbitrarily long string integer? Leading zeros, are they allowed?
I ask the above because the existing code offered will return true for “is int” in cases where you, possibly, may not want them to do so. For example, FILTER_VALIDATE_INT will allow a sign and is bound by the integer range of PHP, and ctype_digit() allows leading zeros but accepts any length of string.
function isInt($input)
{
return preg_match("/^[0-9]+$/",trim($input));
}
(or something like that - I’m not at my normal PC)
And this works fine for what I want (although other solutions may be slightly faster). Ie to allow only whole, simple, positive numbers, whether it be an integer literal or a string literal. No decimals. no signs. No other string characters. Basically what you’d expect out of a database auto increment primary key.
I was just wondering if I had been missing some native PHP function to do this, but I guess there isn’t one because I’m actually wanting to exclude some valid integer elements like signs.