Amila Jack
Amila Jack

Reputation: 87

PHP Array reference, modifying array values

I'm trying to modify an array when looping through it and increment certain values.

     $data = ['traits' => [[['amt' => 1]]]];
     var_dump($data['traits']);

      foreach ($data['traits'] as $key => &$index) {

        foreach ($index as $key => &$value) {

          $value['amt'] = $value['amt']++; // This should increment

          if (in_array($key, $input)) {
            $i++;
            $insert["field_".$i] = $key."_1";
          }
        }
      }

      var_dump($data['traits']);    // SAME AS PREVIOUS VAR_DUMP

Upvotes: 0

Views: 42

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173642

What you are doing in the loop is undefined:

$value['amt'] = $value['amt']++;

The outcome of that depends on what's evaluated first. In this case $value['amt']++ seems to be evaluated first and then assigned to $value['amt'] again; the side effect of the increment is lost.

On the other hand, the following statement will work as expected:

$value['amt']++;

Upvotes: 1

Related Questions