Treat an array as circular array when selecting elements – PHP [duplicate]

Get the size of the circular array ($circsize)and then mod the value $i against it and use that as your index:

$mainArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$size      = count($mainArray);
$circular  = array('A', 'B', 'C');
$circsize  = count($circular);

for($i = 0; $i < $size; $i++) {
   echo $mainArray[$i] . ' = ' . $circular[$i % $circsize] . ', ';
}

Leave a Comment