更简洁的检查数组是否仅包含数字(整数)的方法

2022-08-30 13:51:13

如何验证数组仅包含整数值?

我希望能够检查数组并最终得到一个布尔值,即数组是否仅包含整数以及数组中是否有任何其他字符。我知道我可以遍历数组并单独检查每个元素,并根据非数字数据的存在返回或:truefalsetruefalse

例如:

$only_integers = array(1,2,3,4,5,6,7,8,9,10);
$letters_and_numbers = array('a',1,'b',2,'c',3);

function arrayHasOnlyInts($array)
{
    foreach ($array as $value)
    {
        if (!is_int($value)) // there are several ways to do this
        {
             return false;
        }
    }
    return true;
}

$has_only_ints = arrayHasOnlyInts($only_integers ); // true
$has_only_ints = arrayHasOnlyInts($letters_and_numbers ); // false

但是有没有一种更简洁的方法可以使用我没有想到的本机PHP功能来做到这一点?

注意:对于我当前的任务,我只需要验证一维数组。但是,如果有一个递归有效的解决方案,我将不胜感激。


答案 1
$only_integers       === array_filter($only_integers,       'is_int'); // true
$letters_and_numbers === array_filter($letters_and_numbers, 'is_int'); // false

它将帮助您将来定义两个帮助器,高阶函数:

/**
 * Tell whether all members of $array validate the $predicate.
 *
 * all(array(1, 2, 3),   'is_int'); -> true
 * all(array(1, 2, 'a'), 'is_int'); -> false
 */
function all($array, $predicate) {
    return array_filter($array, $predicate) === $array;
}

/**
 * Tell whether any member of $array validates the $predicate.
 *
 * any(array(1, 'a', 'b'),   'is_int'); -> true
 * any(array('a', 'b', 'c'), 'is_int'); -> false
 */
function any($array, $predicate) {
    return array_filter($array, $predicate) !== array();
}

答案 2
 <?php
 $only_integers = array(1,2,3,4,5,6,7,8,9,10);
 $letters_and_numbers = array('a',1,'b',2,'c',3);

 function arrayHasOnlyInts($array){
    $test = implode('',$array);
    return is_numeric($test);
 }

 echo "numbers:". $has_only_ints = arrayHasOnlyInts($only_integers )."<br />"; // true
 echo "letters:". $has_only_ints = arrayHasOnlyInts($letters_and_numbers )."<br />"; // false
 echo 'goodbye';
 ?>