如何知道数组指针何时到达了没有任何项的末尾


How to know when an array pointer has reached the end where's there are no items

我现在使用end()来获取最后一个数组项,但我不希望这样。

我想知道什么时候没有项目,并从数组的开头开始。

$current = $_SESSION['current_song'];
$song_array = explode(',', $_SESSION['song_array']);
$nextkey = array_search($current, $song_array) + 1;
$last_song = end($song_array);
if ($nextkey == count($song_array)){ 
    $nextkey == 0;
}
$next = $song_array[$nextkey];
if ($next == $last_song){
    $sid = $song_array[0];
} else {
    $sid = $next;
}
while($element = current($song_array)){
   // for every item, until we reach the end of the array
   // print_r($element) and see what you have...
   // when finished, move to next element
   next($song_array);
}
// reset pointer to the beginning, if you like
reset($song_array);

如果您需要多次调用它,可能会满足您的需求:

// move pointer to next song
function findnext(&$song_array, $current)
{
    do {
        if (false === next($song_array)) {
            reset($song_array);
        }
    } while (current($song_array) != $current);
    // get next item, rewinding the array if needed
    return next($song_array) ?: reset($song_array);
}
$next = findnext($song_array, $current);