PHP array_Shift() 突然停止

标签 php arrays indexing element

我得到了这个简单的例子来说明我遇到了什么问题。

假设你有:

$myArray =  array("A","B","C","D","E","F","I","G","H");

目标是在循环中删除此数组的第一个元素。

假设:

for($i=0; $i<count($myArray ); $i++){

    var_dump($myArray );

//...Remove the first Element of this array while $i is less than it's length.

    array_shift($myArray); 
}

这会删除第一个 loop 中的第一个 element 和另外两个或三个,突然,它放弃删除第一个 Elements

根据文档:

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. And the it suggests this example.

   <?php 
         $stack = array("orange", "banana", "apple", "raspberry"); 
         $fruit = array_shift($stack); 
print_r($stack); 
?>

输出:数组( [0] => 香蕉 [1] => 苹果 [2] => 覆盆子)

示例清楚地显示了我想要的。但是,为什么它不继续删除到最后一个元素

如果它是这样设计的。然后无论如何要实现第一个Array Element 到最后一个元素的Removal/Deletion ... 直到 count($myArray) 返回 0 (零)。??

非常感谢任何建议。

最佳答案

简单地:

while (count($myArray) > 0) {
    array_shift($myArray); 
}

See Demo

关于PHP array_Shift() 突然停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24256842/

相关文章:

python - 如何在 Python 中 gzip 字节数组?

javascript - MongoDB选择_id数组的位置?

python - 使用具有冗余元素的 python 数组索引 python 数组

arrays - isnan 索引

c# - 在 C# 中查找字符串中的所有模式索引

PHP readfile 文件的大小正在增加

php - MySql 连接查询在本地服务器上工作,但在实时服务器上不工作

php - 为什么配置数组在 PHP 和 Javascript 中是可接受的参数?

php - Doctrine 无法连接到链接的 docker 容器中的 MYSQL 数据库

python - 类型代码 'c' 不适用于 python 3.5 中的数组定义