I must check big arrays to see if they are 100% filled with numeric values. The only way that comes to my mind is foreach and then is_numeric for every value, but is that the fastest way?
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.
Checking array elements using the for loop First, initialize the result variable to true . Second, iterate over the elements of the numbers array and check whether each element is less than or equal zero. If it is the case, set the result variable to false and terminate the loop immediately using the break statement.
In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.
assuming your array is one-dimensional and just made up of integers:
return ctype_digit(implode('',$array));
Filter the array using is_numeric. If the size of the result is the same as the original, then all items are numeric:
$array = array( 1, '2', '45' );
if ( count( $array ) === count( array_filter( $array, 'is_numeric' ) ) ) {
// all numeric
}
array_map("is_numeric", array(1,2,"3","hello"))
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => )
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