PHP foreach value by reference
Mike Milano — July 1, 2008 - 10:49pm
[img_assist|nid=9|title=|desc=|link=none|align=right|width=100|height=66] PHP5 added a very subtle yet very handy feature in the foreach Control Structure. It is the ability to access the value in the iteration as a reference to the original array.
The best way to demonstrate this is to establish an objective.
There's at least 3 general ways we could go about this but obviously I'd like to show you how this can be accomplished using foreach with the value of each iteration as a reference.
<?php function capitalizeArray($array) { // make sure input is an array, and return an array if it isn't just to be nice. if (!is_array($array)) { return array(); } // create a foreach structure with '&' before the value to access it as a reference foreach ($array as &$value) { // set $value t uppercase $value = strtoupper($value); } // return the array return $array(); } ?>
Notice we did not need to access the original array with a key to change the values inside of it. i.e. $array[0] = strtoupper($array[0]);
Remember that this will not work in PHP4 so don't use it if your code needs to be backwards compatible.

Thank you very much for this
Anonymous (not verified) — January 28, 2011 - 7:56amThank you very much for this tutorial. It's been rather helpful. I only wanted to emphasize readers' attention on the thing that when using foreach to pass an array's key ($key => $value), the key must be a string and not binary content - containing 0's, f.e., as was my case when i used foreach to parse bencoded data handed back to me from a bittorrent tracker scraping - as this will throw foreach off and hand you a key that is binary different than the actual content of the array.
Thank you very much for this
Anonymous (not verified) — January 28, 2011 - 7:38amThank you very much for this tutorial. It's been rather helpful. I only wanted to emphasize readers' attention on the thing that when using to pass an array's key ($key => $value), the key must be a string and not binary content - containing 0's, f.e., as was my case when i used foreach to parse bencoded data handed back to me from a bittorrent tracker scraping - as this will throw foreach off and hand you a key that is binary different than the actual content of the array.
Post new comment