简体   繁体   English

检查数组是否为数字的最佳方法

[英]Best way to check if array is numeric

Say i have a one dimensional array of 500,000 cells and I want to know if this array is numeric, the most obvious options are either to iterate on the whole array and use the is_numeric() function or to use an array_shift. 假设我有一个包含500,000个单元的一维数组,我想知道该数组是否为数字数组,最明显的选择是遍历整个数组并使用is_numeric()函数或使用array_shift。 The problem with that is that both of these options are O(n) (correct me if I'm wrong) and will be more expensive as the data in the array grow. 问题在于这两个选项均为O(n)(如果我写错了,请纠正我),并且随着数组中数据的增长而变得更加昂贵。 I'm thinking of another way but I'm not sure of its O, which is to search for all the non numeric values in the array using regex and array_search. 我在想另一种方法,但我不确定它的O,即使用regex和array_search在数组中搜索所有非数值。 What do you think and are there any less expensive options? 您如何看待,还有没有更便宜的选择?

Would implode be efficient? 内爆会有效吗? If you have a simple array, I would join all the elements together into a string and run it against is_numeric. 如果您有一个简单的数组,我会将所有元素连接到一个字符串中,并针对is_numeric运行它。 At least you would only have to do the numeric check once. 至少您只需要执行一次数字检查。

$foo = array(1, 2, 3, 4, 5, 6, ....);
$bar = implode('', $foo);

var_dump(is_numeric($bar));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM