脚本宝典收集整理的这篇文章主要介绍了PHP foreeach删除数组元素,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
if ($this->minimuMLength > 1) { foreach ($string as &$word) { if (strlen($word) < $this->minimumLength) { unset($word); } } }
奇怪的是,这会在我的数组中留下一些低于允许长度的单词.在我整个班级寻找错误之后,我试了一下:
if ($this->minimumLength > 1) { foreach ($string as $key => $word) { if (strlen($word) < $this->minimumLength) { unset($string[$key]); } } }
瞧!这非常有效.现在,为什么会发生这种情况?我检查了PHP Documentation,它说:
当您通过引用迭代时,迭代变量是原始的别名.当您使用此别名来引用原始别名并修改其值时,更改将在正在迭代的数组中保持可见.
但是,当您取消设置别名时,原始变量不会被“销毁”;别名只是从符号表中删除.
foreach ($string as $key => &$word) { // This does not mean that the word is removed From $string unset($word); // IT simply means that you cannot refer to the iteration VARiable using // $word from this point on. If you have captured the key then you can // still refer to it with $string[$key]; otherwise,you have lost all handles // to it for the remainder of the loop body }
以上是脚本宝典为你收集整理的PHP foreeach删除数组元素全部内容,希望文章能够帮你解决PHP foreeach删除数组元素所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。