更简洁的方法来检查数组是否只包含数字(整数) [英] More concise way to check to see if an array contains only numbers (integers)

查看:27
本文介绍了更简洁的方法来检查数组是否只包含数字(整数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果数组只包含整数和 false 如果有任何其他数组中的字符.我知道我可以遍历数组并单独检查每个元素并根据非数字数据的存在返回 truefalse:

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. 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:

例如:

$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 功能来做到这一点?

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

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

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

这篇关于更简洁的方法来检查数组是否只包含数字(整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆