You can in fact use foreach to change array elements in PHP

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));
}

Leave a Comment for You can in fact use foreach to change array elements in PHP