0

I need to be able to loop an array of items and give them a value from another array and I cant quite get my head around it.

My Array

$myarray = array('a','b','c'); 

Lets say I have a foreach loop and I loop through 6 items in total.

How do I get the following output

item1 = a
item2 = b
item3 = c
item4 = a
item5 = b
item6 = c

My code looks something like this.

$myarray = array('a','b','c'); 
$items = array(0,1,2,3,4,5,6);
foreach ($items as $item) {
   echo $myarray[$item];
}

Online example. http://codepad.viper-7.com/V6P238

I want to of course be able to loop through an infinite amount of times

3
  • use a foreach loop nested in a for loop, run the for loop for as long as you want it to run Commented Aug 1, 2012 at 17:33
  • Use a for loop. Additionally, what have you tried? Commented Aug 1, 2012 at 17:33
  • ive tried a for loop and i obviously get stuck every I reach item 4, as there is no corresponding key/value in $myarray Commented Aug 1, 2012 at 17:37

3 Answers 3

6
$myarray = array('a','b','c'); 
$count = count($myarray);
foreach ($array as $index => $value) {
  echo $value . ' = ' . $myarray[$index % $count] . "\n";
}

% is the modulo-operator. It returns

Remainder of $a divided by $b.

what means

0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1

and so on. In our case this reflects the indices of the array $myarray, that we want to retrieve.

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

8 Comments

Why $index % $count if you're only doing one foreach anyway? It's still the same as $index.
@Palladium No, it isn't. $index is the index of the current $value, whereas $count is a static value.
Yes it is. $index, being defined as the numeric keys of the elements, will never be higher than $count (given his test array). Your cases of 3%3 and 4%3 will never happen in your foreach loop.
@Palladium In his example the OPs speaks from an array with size 6 items in $array (in his edit he called it $items), but $myarray is of size 3, thus it will happen.
@Palladium The sentence "Lets say I have a foreach loop and I loop through 6 items in total." stands there right from the beginning ....
|
1

If you want an arbitrary number of loops to be done, you can use the modulus operator to cycle through your keys:

$loop = //how much you want the loop to go
//...
for ($i = 0, $i < $loop, $i++) {
    $key = $i % count($myarray);
    echo $i, ' = ', $myarray[$key];
}

Comments

1

I think what you are looking for is the modulo operator. Try something like this:

for ($i = 1; $i <= $NUMBER_OF_ITEMS; $i++) {
    echo "item$i = ".$myarray[$i % count($myarray)]."\n";
}

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.