I have an associative array, i.e.
$primes = array( 2=>2, 3=>3, 5=>5, 7=>7, 11=>11, 13=>13, 17=>17,
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 goes 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 destroys the pointer of the array that I am executing.
I would like to be able to save and restore the internal array pointer in the IsPrime () function, so it does not have this side effect. Is there any way to do this?
source share