0

I am trying to get the $current_account in a foreach loop until the fooreach loops ends. I am using the next function which gives me the next element in an array until it reaches the end. How can I make it go to the first element in the array once it reached the end of the array?

$search_tags = array(
    "happy",
    "summer",
    "beach",
    "glasses",
    "umbrella",
    "funny",
    "people",
    "music",
    "rap"
);

$accounts = array(
    "account A",
    "account B",
    "account C"
);

foreach ($search_tags as $tag) {
    $current_account = current($accounts);
    print_r($current_account."\n");

};

So in this case the result should be like this:

Account B Account C Account A Account B Account C Account A Account B Account C Account A

But I am getting the following:

Account B Account C

Jonas
  • 121,568
  • 97
  • 310
  • 388

2 Answers2

4

Use InfiniteIterator

$accounts = new InfiniteIterator(new ArrayIterator($accounts));
$accounts->rewind();

foreach($search_tags as $tag) {
    echo ucfirst($accounts->current()), PHP_EOL;
    $accounts->next();
}

See Live Demo

Baba
  • 94,024
  • 28
  • 166
  • 217
0

There are other simple ways of doing this, such as by accessing the accounts elements by index depending on the current index, as below;

foreach ($search_tags as $index => $tags) {
    print_r($accounts[$index % count($accounts)] . "\n");
}

Which outputs;

account A
account B
account C
account A
account B
account C
account A
account B
account C
Pudge601
  • 2,048
  • 1
  • 12
  • 11