note 57312 added to language.types.array
| From: | ia | Date: | Fri, 30 Sep 2005 09:55:37 +0000 |
| Subject: | note 57312 added to language.types.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-96035@lists.php.net to get a copy of this message | ||
Regarding the previous comment, beware of the fact that reference to the last value of the array
remains stored in $value after the foreach:
<?php
foreach ( $arr as $key => &$value )
{
$value = 1;
}
// without next line you can get bad results...
//unset( $value );
$value = 159;
?>
Now the last element of $arr has the value of '159'. If we remove the comment in the
unset() line, everything works as expected ($arr has all values of '1').
Bad results can also appear in nested foreach loops (the same reason as above).
So either unset $value after each foreach or better use the longer form:
<?php
foreach ( $arr as $key => $value )
{
$arr[ $key ] = 1;
}
?>
----
Manual Page -- http://www.php.net/manual/en/language.types.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+57312
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+57312&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+57312&report=yes
Search -- http://master.php.net/manage/user-notes.php