Recently I read somewhere that you can’t do this and you have to use this awful syntax:
foreach ($array as &$value) {}
This is only valid in PHP5 and can have very bad consequences for example run this piece of code:
<pre><?php $array = array(1, 2, 3, 4, 5); foreach ($array as &$value) { echo "$value \n"; } echo "\n\n"; foreach ($array as $value) { echo "$value \n"; } ?>
Here first foreach loop is foreach by reference but the second one is a normal foreach loop.
Run it and see what happens.
The way to change the elements using foreach is very simple actually, the only thing you need is a $key along with the $value!
/* Filter the input */ foreach ($_POST as $key => $value) { $_POST[ $key ] = trim(strip_tags($value)); }
I'm the co-founder of
I did a quick google to find out if I could use the foreach($array as $key=>value){..} to update arrays and this was the first thing that came up…
I’m traversing through a multi-dimensional JSON file as an array in PHP and one mistake would have had me spending hours fixing it!
Thankyou for saving me so much time!
Comment
Actually the original example works just fine. You need to unset the value after the loop: unset($value)
This is a good practice to follow, along with reseting your array before using it in a loop.
Have a good day.
Comment
Just want to correct Anon’s post:
When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.
Comment