How to store and reset a PHP array pointer

I have an associative array, i.e.

$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 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?

+4
source share
5 answers

Do not rely on array pointers. Use iterators instead.

You can replace the external code as follows:

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

You can "save" the state of the array:

 $state = key($array); 

And "restore" (not sure if there is a better way):

 reset($array); while(key($array) != $state) next($array); 
+4
source

If speed is not a problem and you do not press php memory limits, the fastest solution is to simply duplicate an array of primes and repeat two different ones.

 $awesomePrimes=$primes; 

Then change globals and foreach in your function to $awesomePrimes

0
source

How to make another array int -> int , where the index is a number from 0 to n, and the value is the index of an associative array? So you will have:

 $pointer = array( 0 => 2, 1 => 3, 2 => 5, // ... ); 

and instead of calling $prime directly, would you use $prime[$pointer[$i]] or something like that?

0
source

use the "for" loop for one of your iterations. for example, use this loop in the IsPrime method:

 $primesLength = count($primes); // this is to avoid calling of count() so many times. for ($counter=0 ; $counter < $primesLength ; $counter++) { $p = $primesLength[$counter]; if( $num % $p == 0 ) return false; if ($p >= $root) break; } 

thus, the internal array pointer will not be used in the method.

0
source

All Articles