views:

86

answers:

2

Hi, I have a function which is called within a foreach loop and takes in two parameters, an integer, representing the number of times the loop has run and an array (of no fixed size).

I would like to return the value of the array key that is equal to the counter.

For example, if the array has four elements: A, B, C and D and the counter is equal to 2, it returns B. However, I'm trying to get the same result if the counter is equal to 6, 10, 14, 38, 3998 etc etc.

Is there a simple way to achieve this?

Any advice appreciated.

Thanks.

+1  A: 
<?php

function foo($position, array $array)
{
    return $array[$position % count($array)];
}

foreach ($array as $i => $whatever) {
    $foo = foo($i, $whatever);
}

Note: I'm assuming you're looping over an array of arrays, and passing that to your function. If that's not the case, then just pass whatever array you need to pass instead of $whatever.

hobodave
Yup, that's what I understood he wants to do, too
Gordon
A: 

If you just use this function to iterate over the array, then you could also do

$iterator= new LimitIterator(                      // will limit the iterations
               new InfiniteIterator(               // will restart on end
                   new ArrayIterator(              // allows array iteration
                       array('A','B', 'C', 'D'))), // the array to iterate over
       0, 20);                                     // start offset and iterations

foreach($iterator as $value) {
    echo $value; // outputs ABCDABCDABCDABCDABCD
}
Gordon