alex77
Новичок
итератор и как работает foreach?
Здравствуйте.
Пытаюсь сделать итератор по свойствам объекта, и задумался как он должен себя вести при unset внутри цикла
a aa
b bb
c cc
d dd
e ee
a aa
b bb
c cc
e ee
http://ru2.php.net/manual/en/control-structures.foreach.php#88578
foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other.
Здравствуйте.
Пытаюсь сделать итератор по свойствам объекта, и задумался как он должен себя вести при unset внутри цикла
PHP:
$a = array('a' => 'aa', 'b' => 'bb', 'c' => 'cc', 'd' => 'dd', 'e' => 'ee');
foreach ($a as $k => $v) {
echo $k.' '.$v.'<br />';
if ('b' == $k) unset($a['d']);
}
foreach ($a as $k => $v) {
echo $k.' '.$v.'<br />';
}
b bb
c cc
d dd
e ee
a aa
b bb
c cc
e ee
http://ru2.php.net/manual/en/control-structures.foreach.php#88578
foreach and the while/list/each methods are not completely identical, and there are occasions where one way is beneficial over the other.
PHP:
<?php
$arr = array(1,2,3,4,5,6,7,8,9);
foreach($arr as $key=>$value)
{
unset($arr[$key + 1]);
echo $value . PHP_EOL;
}
?>
Output:
1 2 3 4 5 6 7 8 9
<?php
$arr = array(1,2,3,4,5,6,7,8,9);
while (list($key, $value) = each($arr))
{
unset($arr[$key + 1]);
echo $value . PHP_EOL;
}
?>
Output:
1 3 5 7 9
PHP: