Jump to content

How can check variable value content integer or not by is_int() ?


man12_patil3

Recommended Posts

I really don't understand why this thread has caused so much confusion. Reg expressions to check if a variable is an integer... really? Why?

Yeah, I know. But apparently an INT field type in the database isn't enough. And it's true that PHP doesn't have a function to check if a numeric string is strictly an integer.

 

If the field type is INT then what else could be returned except for a string containing an INT?

is_int() won't tell you if a numeric string represents an integer; is_int('123'); returns FALSE.

 

Oh, I misread. That's funny. You'd think they would have one.

 

I suppose:

$val = intval($val);
echo is_int($val);

 

Would work.

This seems to have morphed into a conversation on more of a theoretical/philosophical plane.

Indeed. It may have to be closed for its own benefit since now I've become part of the problem I was talking about earlier.

I suppose:

$val = intval($val);
echo is_int($val);

 

Would work.

Actually no. If $val isn't a valid integer then intval() will return 0. It always returns an integer so is_int(intval($variable)) is always true.

I suppose:

$val = intval($val);
echo is_int($val);

 

Would work.

Actually no. If $val isn't a valid integer then intval() will return 0. It always returns an integer so is_int(intval($variable)) is always true.

 

That's pretty annoying. I would say check if the value was 0 but 0 itself is a possible integer. Seems like you would have to check if the variable was 0 then echo intval.

 

Seems overcomplicated. I'll stick to not using 0 as an integer.

I really like Pikachu's solution (modified slightly)

 

<?php 

$values = array( 15.1, -20, '4524', 15, 'zomg', '-434', '12.5', '--10' );

foreach( $values as $v ) {
var_dump($v);
echo ( isInt($v) ? '<font color="green">is ' : '<font color="red">is not ' ).' an integer or integer string</font><br>';
}

function isInt( $n ) {
$n = (string) $n;
return ctype_digit($n[0]=='-'?substr($n,1):$n);
}

?>

 

Or one line

return ctype_digit( substr($n,0,1)=='-'?substr($n,1):(string)$n );

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.