Using Foreach in PHP

Asked

Viewed 228 times

4

The builder foreach provides an easy way to iterate on arrays. In several scripts we can observe the following usage:

foreach ($array as $value) {
    $value = $value * 2;
}

However, in some cases the following use:

foreach ($array as &$value) {
    $value = $value * 2;
}

What exactly would be the character & accompanied by the variable $value, and what its effect within the command foreach?

  • 2

    & means you’re using the reference. Thus $value has a reference to a position of your array, changing $value the value is changed at the position of your array automatically.

  • 2

    Example at this link: https://answall.com/q/158546/57801

  • If in foreach without reference, I modify the value of $value, I won’t be changing the value within the array?

  • 1

    No, you need to re-assign to the array, or the change is only in the variable as long as it exists in the cycle, when the cycle is completed the change is lost and in the new cycle the next position of the array is assigned.

  • 1

    PHP documentation: http://php.net/manual/en/language.references.whatdo.php

  • In the following case, I make changes without the reference and they are maintained, see: http://sandbox.onlinephpfunctions.com/code/ee080b3cf307eb359545e8d6594f32d6a208acf6

  • It’s the same principle as the reference, you’re instantiating a class and putting it inside an array, but the classes work directly with reference. Thus, if you change any class attribute, all the places that have the class reference will be changed as well. An example is this one, created a class and assigned 2 variables, changing the value in one of them will change in the other.

Show 2 more comments

1 answer

2


The use of the second way refers to the passage by reference, that is, if you change the value it contains in $value will change at the memory position of the array being traversed.

To better understand:

What references do

References in PHP allow you to create two or more variables that refer to the same content. That is, when you do:

<?php
$a =& $b;
?>

so here $a and $b point to the same content. Changing any of the two variables the content is automatically changed in the other, as they are linked to the same memory position.

Source

One should check if there are any performance issues, there is a topic on this

Foreach by reference or value?

Regarding the commenting, in this case you are changing the value of a class and not a value in the array.

Changing the class attribute will change where all instances of it are.

Example: http://sandbox.onlinephpfunctions.com/code/be707e3b92448c5ce26c56dda7e98edeb74054ec

Browser other questions tagged

You are not signed in. Login or sign up in order to post.