如何存储和重置一个PHP数组指针? [英] How to store and reset a PHP array pointer?

查看:348
本文介绍了如何存储和重置一个PHP数组指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关联数组,即

$primes = array(
  2=>2,
  3=>3,
  5=>5,
  7=>7,
  11=>11,
  13=>13,
  17=>17,
  // ...etc
);

然后我

// 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;
}

问题在于IsPrime也遍历$素阵列

The problem is that IsPrime also loops through the $primes array,

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;
}

这象垃圾一样清除数组指针我对迭代

which trashes the array pointer I am iterating on.

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

I would like to be able to save and restore the array's internal pointer in the IsPrime() function so it doesn't have this side effect. Is there any way to do this?

推荐答案

不要依赖数组指针。使用迭代器来代替。

Don't rely on array pointers. Use iterators instead.

您可以取代你的外code:

You can replace your outer code with:

foreach ($primes as $p) {
  if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) {
    return $p;
  }
}

这篇关于如何存储和重置一个PHP数组指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆