在PHP中获取并删除数组的第一个元素


Get and remove first element of an array in PHP

Hi我正在编写一个系统,在这个系统中,我需要一个函数来获取和删除数组的第一个元素。此阵列有数字,即

0,1,2,3,4,5

我如何循环遍历这个数组,每次遍历都得到值,然后从数组中删除它,这样在5轮结束时,数组将为空。

提前感谢

您可以使用array_shift进行以下操作:

while (($num = array_shift($arr)) !== NULL) {
  // use $num
}

您可以尝试使用foreach/unset,而不是array_shift。

$array = array(0, 1, 2, 3, 4, 5);
foreach($array as $value)
{
    // with each pass get the value
    // use method to doSomethingWithValue($value);
    echo $value;
    // and then remove that from the array 
    unset($array[$value]);
}
//so at the end of 6 rounds the array will be empty
assert('empty($array) /* Array must be empty. */');
?>