0

I try to add new data in a multidimensional array for each loop, but it wont work.

This shows the values in my array:

   $keys = array_keys($klanten);
    for($i = 0; $i < count($klanten); $i++) {
      foreach($klanten[$keys[$i]] as $key => $value) {
            echo $key . " : " . $value . "<br>";
            $klanten['newData'] = 'test';
        }
     }

With $klanten['newData'] = 'test'; I try to add "test" to each array, but it won't work.

I also tried to use this, AFTER the script above:

    foreach ($klanten as &$item ){
        $item['newData'] = 'test';
    }

That will work, but I think there must be an option to do it in the foreach loop above the first time. How can I do that?

1 Answer 1

1

Hi so you got most of it right but, you see when you are looping around a variable and adding a new item in it you have to make sure to give a index for that new array index so...

$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
  foreach($klanten[$keys[$i]] as $key => $value) {
        echo $key . " : " . $value . "<br>";
        // $klanten['newData'] = 'test'; // instead of this
        $klanten[$key]['newData'] = 'test'; // do this
    }
 }

This will save each and every value of newData index according to its key in $klanten array.

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.