Foreach behavior with variables by reference

3

I was doing some testing and I noticed that foreach behaves oddly.

Suppose I have the following array :

$array = array('primeiro', 'segundo', 'terceiro');

When I run a foreach using a reference, and then another foreach without a reference (with the same variable), see what happens:

$array = array('primeiro', 'segundo', 'terceiro');

foreach ($array as &$b);

var_dump($array);

foreach ($array as $b);

var_dump($array);

Result:

array (size=3)
  0 => string 'primeiro' (length=8)
  1 => string 'segundo' (length=7)
  2 => &string 'terceiro' (length=8)

array (size=3)
  0 => string 'primeiro' (length=8)
  1 => string 'segundo' (length=7)
  2 => &string 'segundo' (length=7)

See that the last element has changed.

Then two questions came up:

  • Is the last value of $array given the value of the penultimate element?
  • Why, after a% with% with variable by reference, the last element is as referenced by the variable (which is after foreach )?

Note : Repair the as sign in the result.

    
asked by anonymous 14.08.2015 / 18:18

1 answer

5

When you "match" two variables, you can do this in two ways:

  • By value : Indicating that at that point in the code the value of one is the same as the other:

    $a = $b;
    
  • By reference : Indicating that, until told otherwise, they are the same, ie what happens to one should happen to the other:

    $b = "b";
    $a = &$b;
    var_dump($a);   //Imprime: var 'b'
    
    $a = 'a';
    var_dump($b);   //Imprime: var 'a'
    

By passing the variable $b by reference in the first foreach, you are, at each iterate, binding the value of $b to a position of the $array vector.

$b = &$array[0];  //na primeira iterada 

When establishing the link with another variable, the first link is broken, that is, in the second iteration $b is linked with $arrray[1] and no longer with $array[0] . In other words, at the end of the first foreach, $b is bound to the (and just the) third position of the vector:

$b = &$array[2];  //na última iterada

In the second foreach, at each iterate, we are saying that $b has a new value, and therefore $arrray[2] also has a new value at each iterate. In the penultimate iteration we do:

$b = $array[1];
//o que implica que também estamos fazendo $array[2] = $array[1];

And so, when we get to the last iteration of the second foreach, the last position is with the penultimate value.

    
15.08.2015 / 02:30