0

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
2
  • Provide your array structure or sample array Commented Nov 26, 2014 at 6:02
  • Replace $key in the inner loop by another variable. In your case it gets overwritten and is not what you intended. And do you really want to set $insert in the if clause? Please explain what you are achieving to do. Commented Nov 26, 2014 at 6:12

1 Answer 1

1

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']++;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.