Naz*_*riy 3 php validation numbers
我有一个二维数组,其中包含必须使用以下规则验证的数字范围,范围应从0开始,然后按算术级数进行.
例如:
$array = array();
$array[] = array(0);//VALID
$array[] = array(0,1,2,3,4,5);//VALID
$array[] = array("0","1");//VALID
$array[] = array(0,1,3,4,5,6);//WRONG
$array[] = array(1,2,3,4,5);//WRONG
$array[] = array(0,0,1,2,3,4);//WRONG
Run Code Online (Sandbox Code Playgroud)
什么是在PHP中最有效的方法?
更新 我忘了添加数字可以表示为字符串
比较它range($firstelt, $lastelt)?
function isProgression($arr){
return $arr == range(0, $arr[count($arr)-1]);
}
Run Code Online (Sandbox Code Playgroud)
完全随意的基准:
function isProgression($array){
return ($array == range(0, $array[sizeof($array)-1]));
}
function isProgression2($array){
$count = count($array);
for ($i = 0; $i < $count; ++$i) {
if($array[$i] != $i){
return true;
}
}
return false;
}
for ($x = 0; $x < 1000000; $x++) {
// Pick one
isProgression(array(0,1,2,3,4,5));
isProgression2(array(0,1,2,3,4,5));
}
Run Code Online (Sandbox Code Playgroud)
结果:
isProgression: 0m2.345s
isProgression2: 0m1.906s
Run Code Online (Sandbox Code Playgroud)