1

I've got an array within arrays and would like to add something to it.

$options = $request->options;
foreach ($options as $option) {
    $option['poll_id'] = $this->id;
}

dd($options);

But for some reason it does not add to the array.

So I receive this:

array:1 [
  0 => array:1 [
    "name" => "testtest"
  ]
]

But I would expect this:

array:1 [
  0 => array:1 [
    "name"    => "testtest",
    "poll_id" => 1 

  ]
]

2 Answers 2

1

You're not changing $options so foreach is destroying $option with each iteration. Try something like this instead:

$options = [];
foreach ($request->options as $key => $value) {
    $options[$key]['poll_id'] = $this->id;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should do it using the $key attribute on arrays

// Suppose your $request->options is like:
$options = [
  0 => [
    "name" => "testtest"
  ]
];

foreach ($options as $key => $option) {
    $options[$key]['poll_id'] = 3; // Changing variable - $options here.
}

and it should work!

// $options would be like:

array:1 [▼
  0 => array:2 [▼
    "name" => "testtest"
    "poll_id" => 3
  ]
]

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.