1

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.

2
  • 1
    Do you have any code to show us? Anything you tried and got stuck on? Commented Feb 19, 2010 at 16:49
  • Can you clarify what you're trying to ask? The sentence "I would like to return the position with in the counter's position within a count of the array parameter" doesn't make any sense to me. Commented Feb 19, 2010 at 16:50

2 Answers 2

1
<?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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, that's what I understood he wants to do, too
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.