PHP foreach and reference

93 views Asked by At

I have one var_dump before and one after to show.

Why (and when) is $data->offers modified as foreach just copy the value in the variable ?

I have this code :

<?php
data = new stdClass();
$data->offers = $this->getOffreChildren(27);
var_dump($data->offers);
foreach ($data->offers as $offre) {
    $offre->contracts = $this->getOffreChildren($offre->id);
    foreach ($offre->contracts as $contract) {
        $contract->count = 0;
        foreach ($adhesions as $adhesion) {
            if ($adhesion->id_type_contrat == $contract->id)
                $contract->count = $adhesion->nombre;
        }
    }
}
var_dump($data->offers); die;

First var dump :

array (size=7)
  0 => 
    object(stdClass)[260]
      public 'nom' => string 'lorem' (length=6)
      public 'id' => string '1' (length=1)
      public 'code' => string 'lorem' (length=5)
  1 => 
    object(stdClass)[261]
      public 'nom' => string 'lorem.... ' (length=19)
      public 'id' => string '2' (length=1)
      public 'code' => string 'lorem..... lorem' (length=13)
  2 => 
    object(stdClass)[262]
      public 'nom' => string 'lorem...lorem' (length=17)
      public 'id' => string '48' (length=2)
      public 'code' => string 'lorem...lorem' (length=16)
   ....

The second var_dump :

array (size=7)
  0 => 
    object(stdClass)[260]
      public 'nom' => string 'lorem' (length=6)
      public 'id' => string '1' (length=1)
      public 'code' => string 'lorem' (length=5)
      public 'contracts' => 
        array (size=14)
          0 => 
            object(stdClass)[258]
              ...
          1 => 
            object(stdClass)[257]
              ...
          2 => 
            object(stdClass)[256]
              ...
  1 => 
    object(stdClass)[261]
      public 'nom' => string 'lorem.... lorem' (length=19)
      public 'id' => string '2' (length=1)
      public 'code' => string 'lorem..... lorem' (length=13)
      public 'contracts' => 
        array (size=4)
          0 => 
            object(stdClass)[270]
              ...
          1 => 
            object(stdClass)[269]
              ...
1

There are 1 answers

0
RST On

Foreach walks your array and in your case adds contracts property to it with the command

$offre->contracts = $this->getOffreChildren($offre->id);

it is not clear where $adhesions comes from but with

$contract->count = $adhesion->nombre;

you add another property to the already added contracts property.