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.