如何添加到正在使用的阵列foreach
上?
例如:
$t =array('item');
$c = 1;
foreach ($t as $item) {
echo '--> '.$item.$c;
if ($c < 10) {
array_push($t,'anotheritem');
}
}
这似乎只产生一个值('item1')。似乎$t
只评估一次(在第一次foreach
使用时),但进入循环后才评估一次。
foreach()
会将您传递给它的数组作为静态结构进行处理,就迭代次数而言,它不能是动态的。您可以通过将迭代的值传递给引用(&$value
)来更改值,但不能在同一控件结构中添加新值。
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()
使用一种while(true){ do }
方法定义自己的自定义循环结构。
免责声明:确保您正在执行此操作,以定义逻辑停止位置的上限。本质上,您要承担确保循环在此处停止的责任,而不是像限制PHP那样给极限foreach()
(数组大小)或for()
传递极限的地方。
$original = array('one', 'two', '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;
}
}
在这里看到差异。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句