检查数组中的所有值是否都是数字的最快方法是什么?

2022-08-30 23:10:32

我必须检查大数组,看看它们是否100%填充了数值。我想到的唯一方法是foreach,然后为每个值is_numeric,但这是最快的方法吗?


答案 1

假设你的数组是一维的,只是由整数组成:

return ctype_digit(implode('',$array));

答案 2

使用is_numeric筛选数组。如果结果的大小与原始结果相同,则所有项目都是数字:

$array = array( 1, '2', '45' );
if ( count( $array ) === count( array_filter( $array, 'is_numeric' ) ) ) {
    // all numeric
}