如何存储和重置 PHP 数组指针?

Hug*_*ell 4 php arrays loops

我有一个关联数组,即

$primes = array(
  2=>2,
  3=>3,
  5=>5,
  7=>7,
  11=>11,
  13=>13,
  17=>17,
  // ...etc
);
Run Code Online (Sandbox Code Playgroud)

然后我做

// seek to first prime greater than 10000
reset($primes);
while(next($primes) < 10000) {}
prev($primes);

// iterate until target found
while($p = next($primes)) {
      $res = doSomeCalculationsOn($p);

      if( IsPrime($res) )
          return $p;
}
Run Code Online (Sandbox Code Playgroud)

问题是 IsPrime 还会遍历 $primes 数组,

function IsPrime($num) {
    global $primesto, $primes, $lastprime;

    if ($primesto >= $num)
        // using the assoc array lets me do this as a lookup
        return isset($primes[$num]);

    $root = (int) sqrt($num);
    if ($primesto < $root)
        CalcPrimesTo($root);

    foreach($primes as $p) {       // <- Danger, Will Robinson!
        if( $num % $p == 0 )
            return false;

        if ($p >= $root)
            break;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

这会破坏我正在迭代的数组指针。

我希望能够在 IsPrime() 函数中保存和恢复数组的内部指针,因此它没有这种副作用。有没有办法做到这一点?

str*_*ger 5

您可以“保存”数组的状态:

$state = key($array);
Run Code Online (Sandbox Code Playgroud)

和“恢复”(不确定是否有更好的方法):

reset($array);

while(key($array) != $state)
    next($array);
Run Code Online (Sandbox Code Playgroud)