Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Quickest Way to Check If All Values in an Array Are Numeric?

Tags:

arrays

php

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?

like image 705
rsk82 Avatar asked Dec 13 '10 07:12

rsk82


People also ask

How do you check if all values in array are numbers?

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.

How do you check all the elements in an array?

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.

How do you check all values of an array are equal or not in Javascript?

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.


3 Answers

assuming your array is one-dimensional and just made up of integers:

return ctype_digit(implode('',$array));
like image 142
bcosca Avatar answered Sep 22 '22 05:09

bcosca


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
}
like image 27
Andy Keith Avatar answered Sep 20 '22 05:09

Andy Keith


array_map("is_numeric", array(1,2,"3","hello"))

Array ( [0] => 1 [1] => 1 [2] => 1 [3] => )
like image 30
Mancy Avatar answered Sep 22 '22 05:09

Mancy