脚本宝典收集整理的这篇文章主要介绍了PHP为foreach中使用的数组添加新密钥,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
例如:
$t =array('ITem'); $c = 1; foreach ($t as $item) { echo '--> '.$item.$c; if ($c < 10) { array_push($t,'anotheritem'); } }
这似乎只产生一个值(‘item1’).似乎$t仅被评估一次(在foreach使用的第一时间),而不是在它进入循环之后.
对于()
for()将允许您添加新的限制,每次都会评估您传递的限制,因此count($your_array)可以是动态的.例:
$original = array('one','two','three'); for($i = 0; $i < count($original); $i++) { echo $original[$i] . PHP_EOL; if($i === 2) $original[] = 'four (another one)'; };
输出:
one two three four (another one)
而()
您还可以使用while(true){do}方法定义自己的自定义while()循环结构.
免责声明:确保您这样做是为了定义逻辑停止位置的上限.你基本上承担了确保循环在这里停止的责任,而不是给予像foreach()那样的限制(数组大小)或者你传递限制的().
$original = array('one','three'); // define some parameters for this example $finished = false; $i = 0; $start = 1; $limit = 5; while(!$finished) { if(isset($original[$i])) { // Custom scenario where you'll add new values if($i > $start && $i <= $start + $limit) { // ($i-1) is purely for demonstration $original[] = 'New value' . ($i-1); } // Regular loop behavior... output and increment echo $original[$i++] . PHP_EOL; } else { // Stop the loop! $finished = true; } }
见差异here.
以上是脚本宝典为你收集整理的PHP为foreach中使用的数组添加新密钥全部内容,希望文章能够帮你解决PHP为foreach中使用的数组添加新密钥所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。