I have an associative array, ie
$primes = array(
2=>2,
3=>3,
5=>5,
7=>7,
11=>11,
13=>13,
17=>17,
// ...etc
);
then I do
// 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;
}
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.
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?