Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and reset a PHP array pointer?

Tags:

arrays

loops

php

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?

like image 714
Hugh Bothwell Avatar asked Jan 23 '23 23:01

Hugh Bothwell


2 Answers

You can "save" the state of the array:

$state = key($array);

And "restore" (not sure if there's a better method):

reset($array);

while(key($array) != $state)
    next($array);
like image 180
strager Avatar answered Jan 29 '23 15:01

strager


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

You can replace your outer code with:

foreach ($primes as $p) {
  if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) {
    return $p;
  }
}
like image 22
troelskn Avatar answered Jan 29 '23 15:01

troelskn