Reply to Re: safe to delete elements of array in foreach

Your name:

Reply:


Posted by Schraalhans Keukenmeester on 05/19/07 04:52

At Fri, 18 May 2007 20:10:57 -0700, ZeldorBlat let his monkeys type:

>> ==================
>
> This suggests that it's safe (from <http://www.php.net/foreach>):
>
> "Unless the array is referenced, foreach operates on a copy of the
> specified array and not the array itself. Therefore, the array pointer
> is not modified as with the each() construct, and changes to the array
> element returned are not reflected in the original array."
>
Okay, well, uhmmm, not so well hidden then.

Try unsetting and/or changing values in a referenced array foreach:
You might not end u with what you expect. I repeated the code in my other
reply, now operating on $value directly:

$array=array('john','james','delilah','mary');
foreach ($array as $key=>&$value) {
if ($value == 'delilah') {
$value ='samson';
}
elseif ($value=='james') {
$value = null;;
}
echo "$key => $value".NEWLINE;
}

foreach ($array as $key=>$value) {
echo "$key => $value".NEWLINE;
}
Output:
0 => john
1 =>
2 => samson
3 => mary
0 => john
1 =>
2 => samson
3 => samson // !!!

Must be some logic for this, but I fail to see it right now.

Sh.

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация