Blowsie
Blowsie

Reputation: 40565

PHP - Sequence through array and repeat [modulo-operator]

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

Upvotes: 0

Views: 6291

Answers (3)

Gordon Bailey
Gordon Bailey

Reputation: 3911

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";
}

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 132051

$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.

Upvotes: 6

Palladium
Palladium

Reputation: 3763

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];
}

Upvotes: 1

Related Questions