简体   繁体   English

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

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

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 true if the array contains only integers and false if there are any other characters in the array.如果数组仅包含整数,我希望能够检查数组并以布尔值为true结束,如果数组中有任何其他字符,则以false I know I can loop through the array and check each element individually and return true or false depending on the presence of non-numeric data:我知道我可以遍历数组并单独检查每个元素并根据非数字数据的存在返回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.但是如果有一个递归的解决方案,我会很感激看到它。

$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();
}
 <?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';
 ?>

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
}

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.但我更喜欢最快的解决方案(这是你提供的)而不是最简洁的。

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

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.使用任何接受用户回调的内置数组函数( array_filter()array_walk() ,甚至像usort()等排序函数)并在回调中抛出异常。 Eg for multidimensional arrays:例如对于多维数组:

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.这当然不是最简洁的,而是一种通用的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM