note 54290 added to control-structures.foreach
| From: | rokas3 at gmail dot com | Date: | Wed, 29 Jun 2005 19:52:43 +0000 |
| Subject: | note 54290 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-91150@lists.php.net to get a copy of this message | ||
One notice that foreach has strange behaviour with copying array. It sometimes doubles one array
item. For example:
<?php
$array = array(
0 => array("one" => "x", "two" =>
"y"),
1 => array("one" => "z", "two" =>
"a"),
2 => array("one" => "b", "two" => "c")
)
foreach ($array as $item) {
echo $item["one"]." - ".$item["two"]."<br />";
}
/*
x - y
z - a
z - a
b - c
*/
This can be avoided with reference:
foreach ($array as &$item) {
echo $item["one"]." - ".$item["two"]."<br />";
}
/*
x - y
z - a
b - c
*/
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54290
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54290&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54290&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54290&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54290&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54290&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54290&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54290&report=yes
Search -- http://master.php.net/manage/user-notes.php