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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3559542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:13:35  来源:igfitidea点击:

More concise way to check to see if an array contains only numbers (integers)

phparrays

提问by John Conde

How do you verify an array contains only values that are integers?

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

I'd like to be able to check an array and end up with a boolean value of trueif the array contains only integers and falseif there are any other characters in the array. I know I can loop through the array and check each element individually and return trueor falsedepending on the presence of non-numeric data:

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

For example:

例如:

$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

But is there a more concise way to do this using native PHP functionality that I haven't thought of?

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

Note: For my current task I will only need to verify one dimensional arrays. But if there is a solution that works recursively I'd be appreciative to see that to.

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

回答by Ionu? G. Stan

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

It would help you in the future to define two helper, higher-order functions:

将来定义两个辅助高阶函数会有所帮助:

/**
 * 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();
}

回答by mcgrailm

 <?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';
 ?>

回答by Marc B

Another alternative, though probably slower than other solutions posted here:

另一种选择,虽然可能比这里发布的其他解决方案慢:

function arrayHasOnlyInts($arr) {
   $nonints = preg_grep('/\D/', $arr); // returns array of elements with non-ints
   return(count($nonints) == 0); // if array has 0 elements, there's no non-ints
}

回答by Matthew

There's always array_reduce():

总是有 array_reduce():

array_reduce($array, function($a, $b) { return $a && is_int($b); }, true);

But I would favor the fastest solution (which is what you supplied) over the most concise.

但我更喜欢最快的解决方案(这是你提供的)而不是最简洁的。

回答by bcosca

function arrayHasOnlyInts($array) {
    return array_reduce(
        $array,
        function($result,$element) {
            return is_null($result) || $result && is_int($element);
        }
    );
}

returns true if array has only integers, false if at least one element is not an integer, and null if array is empty.

如果数组只有整数,则返回 true,如果至少有一个元素不是整数,则返回 false,如果数组为空,则返回null

回答by postrel

Why don't we give a go to Exceptions?

我们为什么不试试 Exceptions 呢?

Take any built in array function that accepts a user callback (array_filter(), array_walk(), even sorting functions like usort()etc.) and throw an Exception in the callback. E.g. for multidimensional arrays:

使用任何接受用户回调(array_filter(), array_walk(),甚至排序函数usort()等)的内置数组函数,并在回调中抛出异常。例如对于多维数组:

function arrayHasOnlyInts($array)
{
    if ( ! count($array)) {
        return false;
    }

    try {
        array_walk_recursive($array, function ($value) {
            if ( ! is_int($value)) {
                throw new InvalidArgumentException('Not int');
            }

            return true;
        });
    } catch (InvalidArgumentException $e) {
        return false;
    }

    return true;
}

It's certainly not the most concise, but a versatile way.

这当然不是最简洁的,而是一种通用的方式。