获取并删除PHP中数组的第一个元素
嗨,我正在编写一个系统,其中我需要一个函数来获取和删除数组的第一个元素。此数组具有数字,即 0,1,2,3,4,5 我如何循环这个数组,每次循环都得到值,然后从数组中删除,这样在5轮结束时,数组将为空 提前感谢您可以使用:获取并删除PHP中数组的第一个元素,php,arrays,get,Php,Arrays,Get,嗨,我正在编写一个系统,其中我需要一个函数来获取和删除数组的第一个元素。此数组具有数字,即 0,1,2,3,4,5 我如何循环这个数组,每次循环都得到值,然后从数组中删除,这样在5轮结束时,数组将为空 提前感谢您可以使用: while (($num = array_shift($arr)) !== NULL) { // use $num } 您可以尝试使用foreach/unset,而不是array\u shift。 $array = array(0, 1, 2, 3, 4, 5); f
while (($num = array_shift($arr)) !== NULL) {
// use $num
}
您可以尝试使用foreach/unset,而不是array\u 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. */');
?>
看看重复的
数组\u shift
就可以了,但是你真的需要增量清空数组吗?不是重复的,我没有取消设置的键,我正在循环。是需要以增量方式清空。我查看了array_shift,但无法判断它是否在返回该数组项后删除了该数组项……正如@sachleen linked文档中所述:“array_shift()将数组的第一个值移位并返回,将数组缩短一个元素”