问题描述:

Imagine a simple, but large array with keys 0 to 100000.

When doing a foreach loop of this array, is it possible to 'seek' ahead without doing something like:

foreach($array as $key=>$value){

if($key<10000){

continue;

}

}

We do this kind of operation once in a while thru our codebase. It seams like a bit of a waste of ticks to go thru each of the keys until key is greater then 10000.

Is this possible in php 5.4?

Thanks.

网友答案:

it was possible even in PHP 2.0FI or ALTAIR BASIC

for($i=10000;$i < count($array);$i++){
}

No doubt some nitpickers will come to tell that doing count($array) 90000 times is a waste of ticks too. However, to get a real performance gain one have to avoid lengthy loops at all.

网友答案:
$rest = array_slice($array, 10000);

Depending on what you want to achieve (here: what you want to do after seeking)

for ($length = count($array), $key = 10000; $key < $length, $key++) {
  $value = $array[$key];
}
网友答案:

Assuming the keys are consecutive integers:

$count = count($array);
for ($key = 10000; $key < $count; ++$key) {
    $value = $array[$key];
}

I'm not sure if count is O(1) though, so if it's not, you might be better off doing:

$key = 0;
while (isset($array[$key])) {
    $value = $array[$key];
    ++$key;
}

Note that array_key_exists would be required if the key could be considered not set yet exist in the array.

网友答案:

Borrowing from this solution, this would do the trick and set the array pointer at the element you want. This would be the closest you get to seeking the array and not just specifying the interval of keys to loop through.

$start = 10000; // or what ever number you're starting at
while(key($array) < $start) next($array);

You can't use this if you plan to use a foreach-loop (as it resets the pointer), but should be good if you iterate the rest of the array like this

$count = count($array);
do {
  $key = key($array);
  $value = current($array);
} while($key < $count);
相关阅读:
Top