John Doe John Doe - 5 months ago 16x
PHP Question

Basic PHP Array Iteration Issue

I hate to be one of "those guys" - I'm very sure the answer is right in front of my face and I simply can't grasp it. However I have tried for the last few hours to figure this out with the help of our friend Mr. Google to no avail.

What I am trying to do is quite simple:

  1. Push a string to an array.

  2. Count through the entries in the array X number of times with an offset, and return the resulting value as a variable.

For all my labor, I have just this:

$newarray = array(1,2,3,4,7,5,8,6,9);

I'd like to be able to count (for example) starting at the number 3, increment by a variable number (for example, 12) in something of a round robin manner. This would put the end of the count at the number 5. I'd then like to take that number (5) and store it in a variable for use on the rest of the page.

Again, I know this should be elementary but for whatever reason I just can't seem to figure it out. Thank you very much for your help.


Here is one of the way:

  1. Changing the position of the desired element to first position
  2. Finally, pick the element which you desire after a circulating through the array.

PHP Code:

function circulateArr($key, $arr)
    foreach($arr as $arrkey => $value)
        if($arrkey != $key)
            $elm = array_shift($arr);
            array_push($arr, $elm);
    return $arr;

$array = array(1,2,3,4,5,6,7,8,9);
$start = 3;
$roundRobin = 12;

$arr = circulateArr(array_search($start, $array), $array); //Repositioning the array

echo $elementChose = $arr[($roundRobin%count($arr))-1]; //Get the array element