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.
To check if an array contains only numbers:Call the every() method, passing it a function. On each iteration, check if the type of of the current element is number . The every method returns true , only if the condition is met for every array element.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values 'True” and “False“.
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:".
$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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With