$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
Does $key mean index of an array?
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
Does $key mean index of an array?
&$variable_name
is PHP's way of doing pass by reference:
See: http://php.net/manual/en/language.references.pass.php
For more of an explaination of what references are see: http://www.php.net/manual/en/language.references.whatare.php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value)
$value = $value * 100;
echo implode(' ', $arr); // 1 2 3 4
foreach ($arr as &$value)
$value = $value * 100;
echo implode(' ', $arr); // 100 200 300 400
got it?
The & tells PHP to make $value a reference to the actual array item, instead of a copy of the array item. Without the &, your code will not actually modify the values within the array.
You have two different questions. To answer your first about the ampersand (&
):
Whenever you see the &
passed in front of a variable, it means that you will be working with the actual variable and not a copy of it. With your example, the $value
would typically be a copy of the actual $value
, so any changes made to that variable would not affect the array. But when you put the &
in front of it, you are working with actual array data.
To answer your second question, yes, the $key
is an index of the array, whether it's numerical or associative.
The &
allows you to change the values in $value
. You can experiment by trying it without. That's called passing by reference.
The example here isn't so great for explaining $key
because you show a regular array rather than an associative array. Here's a better example to illustrate $key
.
$a = array(
"red" => 1,
"green" => 2,
"blue" => 3,
"white" => 17 /* btw, I patent the white pixel! */
);
foreach ($a as $key => $value) {
echo "key $key, val $value";
}