I had just posted a thread on inbuilt iterator classes. W/o using an iterator class… is there a way move the array pointer to a specific value?
For example lets say I had an array with 1000+ items! I know I dont need to search through the first 550. is there a way to set the pointer to the 550th item and start the loop there?
BTW, I know a foreach resets the counter, but I am not sure if a while loop would work…
Ok, but it just seems like, if you had a large array, to go trough a percentage of the loop simply to REACH the part of the array you want to work with would be a somewhat inefficient use of computer power…
array_chunk( your array, size to split into, [BOOL preserve keys]);
In the above case, if you wanted to split the first 3 results you would have to join the remaining arrays back together again in order to have a new array without the first 3.
Anthony,
So I take it the only way to move the array pointer is one key at a time?
Zurev
incidentally… for seeking a particular key array , I came up with the following method. The only problem is it doesn’t actually move the pointer unless I add a loop…
function seek($arr, $order){
$kmap=array_keys($arr);
return $arr[$kmap[$order]];
}
I suppose I will have to stick to loops. It would be have been nice tho, if you could START an iteration or use each() at a specific point in the array (as oppose to walking up from 0)
With regards to seeking to an offset (not a key), there was some discussion about adding such a function on the PHP internals mailing list ([PHP-DEV] array_seek function) but nothing came of it.
My opinion for this thread is that you’re doing it wrong. If you only want to iterate over a part of the array, is there any reason that you can think of as to why you cannot make a new array containing only the items that you are interested in. array_slice() is fine for that. Of course there are other options like using a LimitIterator on an ArrayIterator, or wrestling with for/while/etc. loops.
It’s a shame this was never added, maybe in my naivety, I think a seek function to move the internal pointer would be an essential part of the standard tool-kit.
PHP has obviously done quite well without it, but it just seems natural to have to this.
I also agree with the point you made on the internal mailing list, a ‘truthy’ seek function would be more suited.