How to wrap around in PHP array when index falls off the end?

こ雲淡風輕ζ 提交于 2019-12-06 03:04:31

You are being far too complex, unless you actually want to process the elements in the array you don't want to iterate over them as it is expensive. I think you just need the modulus of the number of elements in the array, like this:-

$my_array = array('zero', 'one','two','three','four','five','six','seven');

function loopArrayValues(array $array, $position)
{
    return $array[$position % count($array)];
}

for($i = 0; $i <= 100; $i++){
    echo "Position $i is " . loopArrayValues($my_array, $i) . "<br/>";
}

Ouput:-

Position 0 is zero
Position 1 is one
Position 2 is two
Position 3 is three
Position 4 is four
Position 5 is five
Position 6 is six
Position 7 is seven
Position 8 is zero
Position 9 is one
Position 10 is two
Position 11 is three
Position 12 is four
Position 13 is five

etc...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!