1

Ok, Stupid question here... just trying to do a search in an array to be sure all of the values are numeric, if not, I need to return false. What's the quickest way to do this. This array could be HUGE. By the way, it's not a multi-dimensional array, and doesn't have any sub-arrays within it. It's just a one level array... example:

array(1, 5, 6, 2, 44, 92, 50, string);

This should return false, cause string is one of the values in the array and is not a number. I mean, is there a faster way to do this than using foreach on the array and using intval on every value??

Thanks guys :)

3 Answers 3

3

You can use is_numeric function -

$count = count($your_array);

for($index=0; $index<$count; $index++)
{
    if( !is_numeric($your_array[index]) )
        return false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

is_numeric is checking the array
@tttony: Sorry, forgot to index it. Thanks for pointing it out!
Thanks, guess I'm going with this one since it has the most up votes. No offense guys.
3
  if(in_array(false, array_map("is_numeric", array(1, 2, 3, 4, 5, "string"))))
    return false;

I have not researched the performance, sorry. But these are inbuilt functions which are allegedly faster than anything custom one can write...

1 Comment

haven't seen that function before. Nice Info this should be the best solution.
1
foreach($array as $value)
{
    if(!is_numeric($value))
    {
       return false;
    }
}

2 Comments

and why have you put the braces on line 3?
it was a shorthand if statement which is (condition ? true : false) but it doesn't work in that situation. Been a while since I used one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.