更简洁的方法来检查,看看是否一个数组只包含数字(整数) [英] More concise way to check to see if an array contains only numbers (integers)
问题描述
如何验证一个数组只包含整数值?
我希望能够检查数组和真正
如果数组只包含整数和假的布尔值结束
如果有阵列中的任何其它字符。我知道我可以遍历数组,并逐个检查每个元素并返回真正
或假
取决于$ P $非数字数据的psence:
例如:
$ only_integers =阵列(1,2,3,4,5,6,7,8,9,10);
$ letters_and_numbers =阵列('一个',1,'B',2,'c'的,3);功能arrayHasOnlyInts($数组)
{
的foreach($数组作为$值)
{
如果(!is_int($值))//有几种方法可以做到这一点
{
返回false;
}
}
返回true;
}$ has_only_ints = arrayHasOnlyInts($ only_integers); //真
$ has_only_ints = arrayHasOnlyInts($ letters_and_numbers); //假
但是有没有这样做,我都没有想到这个使用本地PHP功能的更简洁的方式?
注:我当前的任务,我将只需要验证一维数组。但如果是递归的工作,我会AP preciative看到解决办法。
$ only_integers === array_filter($ only_integers,'is_int'); //真
$ letters_and_numbers === array_filter($ letters_and_numbers,'is_int'); //假
这将有助于你在未来定义两个帮手,高阶函数:
/ **
* $告诉阵列的所有成员是否验证$predicate。
*
*所有(阵列(1,2,3),'is_int'); - >真正
*所有(阵列(1,2,'A'),'is_int'); - >假
* /
所有功能($数组,$predicate){
返回array_filter($数组,$predicate)=== $阵列;
}/ **
* $告诉阵列中的任何成员是否验证$predicate。
*
*任何(阵列(1,'A','B'),'is_int'); - >真正
*任何(阵列('A','B','C'),'is_int'); - >假
* /
任何功能($数组,$predicate){
返回array_filter($数组,$predicate)==阵列()!;
}
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. 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:
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?
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屋!