user3313329
user3313329

Reputation:

PHP array - start at beginning if over

I have an array with 3 entries like that:

0 => "Banana",
1 => "Apple",
2 => "Strawberry"

Now, when using a for-loop like:

for($i = 1; $i < $foo; $i++) {
  $myarray[$i] = $fruitarray[$i];
}

And $i gets higher than 2, we run out of this $fruitarray. So what I want to do now is always to start at the beginning of the array when it's over. So that 3 outputs "Banana", 7 "Apple" etc.

What is the best practice to achieve this (especially if $fruitarray contains many entries)?

Upvotes: 0

Views: 116

Answers (5)

kojiro
kojiro

Reputation: 77137

Doing this with eager code is essentially intractable, as it would cause an infinite loop:

$i = 0;
$numFruits = count($fruitarray);
while (true) { // infinite loop!
    $myarray[$++i] = $fruitarray[$i % $numFruits];
}

But you can come up with working code if, instead of an array, you use a function to fetch the value:

function getFruitAt($index) use ($fruitarray) {
    $numFruits = count($fruitarray);
    $realIndex = $index % $numFruits;
    return $fruitarray[$realIndex];
}

Or, if you want to get fancy, you can use a generator or define your own Iterator type.

Upvotes: 0

Javier G&#225;lvez
Javier G&#225;lvez

Reputation: 186

You should to use the modulus operator (Modulus remainder of $a divided by $b)

for($i = 1; $i < $foo; $i++) {
  $j=$i%count($fruitarray);
  $myarray[$i] = $fruitarray[$j];
}

http://php.net/manual/en/language.operators.arithmetic.php

Upvotes: 0

Josh.F
Josh.F

Reputation: 3806

for($i = 1; $i < $foo; $i++) {
  $myarray[$i] = $fruitarray[$i%3];
}

Notice the $i%3, this is pronounced "i mod 3" and it means divide i by 3, and return the leftovers. So, 4%3=1, 7%3=1, 11%3=2, etc.

Just make sure $foo is more than 3, and this should wrap around. If $fruitarray is arbitrarily bigger than 3 items, use

$i%count($fruitarray)

Upvotes: 0

Sam Dufel
Sam Dufel

Reputation: 17598

This is generally accomplished using the modulo operator.

for($i = 1; $i < $foo; $i++) {
    $myarray[$i] = $fruitarray[$i % count($fruitarray)];
}

http://php.net/manual/en/language.operators.arithmetic.php

Upvotes: 5

Florin Stingaciu
Florin Stingaciu

Reputation: 8285

One possible solution would be to check for when $i is equal to $foo - 1 and reset it to 1:

for($i = 1; $i < $foo; $i++) {
  $myarray[$i] = $fruitarray[$i];
  if($i == ($foo - 1))
     $i = 1;
}

Upvotes: 0

Related Questions