Ben iki kez bu dizi yineleme Neden PHP (referans değerine göre) değerlerin üzerine yok

2 Cevap php

Ben değerine göre iki kez, referans ve daha sonra bir dizi yineleme ben her döngü için aynı değişken adını kullanırsanız, PHP dizideki son değeri üzerine olacaktır. Bu iyi bir örnek ile gösterilmiştir:

$array = range(1,5);
foreach($array as &$element)
{
  $element *= 2;
}
print_r($array);
foreach($array as $element) { }
print_r($array);

Çıktı:

Array ([0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10)

Array ([0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 8)

Ben bir düzeltme için arıyorum değil unutmayın, ben bu neden oluyor anlamak için arıyorum. Ayrıca her döngüde değişken isimleri $element denilen her değilse bu olmaz unutmayın, bu yüzden $element hala kapsam ve referans olmak ile ilgisi var tahmin ediyorum ilk döngünün sonunda.

2 Cevap

After the first loop $element is still a reference to the last element/value of $array.
You can see that when you use var_dump() instead of print_r()

array(5) {
  [0]=>
  int(2)
...
  [4]=>
  &int(2)
}

Note that & in &int(2).
With the second loop you assign values to $element. And since it's still a reference the value in the array is changed, too. Try it with

foreach($array as $element)
{
  var_dump($array);
}

as the second loop and you'll see.
So it's more or less the same as

$array = range(1,5);
$element = &$array[4];
$element = $array[3];
// and $element = $array[4];
echo $array[4];

(Sadece döngüler ve çarpma ile ... hey, dedim "fazla veya daha az" ;-))

İşte an explanation from the man himself:

$y = "some test";

foreach ($myarray as $y) {
    print "$y\n";
}

Here $y is a symbol table entry referencing a string containing "some test". On the first iteration you essentially do:

$y = $myarray[0];  // Not necessarily 0, just the 1st element

So now the storage associated with $y is overwritten by the value from $myarray. If $y is associated with some other storage through a reference, that storage will be changed.

Şimdi bunu diyelim:

$myarray = array("Test");
$a = "A string";
$y = &$a;

foreach ($myarray as $y) {
    print "$y\n";
}

Here $y is associated with the same storage as $a through a reference so when the first iteration does:

$y = $myarray[0];

The only place that "Test" string can go is into the storage associated with $y.