更新时间:2023-11-28 15:02:04
$ 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();
}