真的没有简单的方法来检查变量是否为整数(无论是字符串类型还是int类型)? [重复]

我需要检查变量是否仅包含整数,并且由于PHP并不真正在意数字是否以STRING类型表示,因此我也不在乎。

But when I use is_int() it returns false for '1' and when I use ctype_digit() it returns false for 1!

And is_numeric(), while accepting both string and float, accepts decimal numbers too.

I'm looking for a function that works like is_numeric() but doesn't accept decimals.

$var[] = 2;
$var[] = '2';

foreach($var as $key => $val){
    if( ! is_int($val) && ! ctype_digit($val)) // <-- Any single function equivalent to these two checks?
        return false;
}

P.S. I'm not lazy, but this has been bothering me for a long time that is_numeric() accepts string format numbers, but is_int() doesn't!

评论
  • <午夜m>
    <午夜m> 回复

    You can do a regex match to check if variable contains only integers using preg_match function

    <?php
    
    if(preg_match('/^\d+$/',$x) === 1){
      // your code goes here
    }