PHP在数组中搜索值 - 如果全部是数字则返回true,否则返回false
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 :)
好的,这里有愚蠢的问题......只是想在数组中进行搜索以确保所有的值 是数字,如果没有,我需要返回false。 什么是最快的方法。 这个数组可能很大。 顺便说一句,它不是一个多维数组,并且其中没有任何子数组。 它只是一个单级数组...例如: p>
array(1,5,6,2,44,92,50,string);
code> pre>
这应该返回false,因为string是数组中的值之一而不是数字。 我的意思是,有没有比在数组上使用 foreach code>并在每个值上使用 intval code>更快的方法? p>
谢谢你们:) p>
div>
You can use is_numeric function -
$count = count($your_array);
for($index=0; $index<$count; $index++)
{
if( !is_numeric($your_array[index]) )
return false;
}
foreach($array as $value)
{
if(!is_numeric($value))
{
return false;
}
}
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...