Array losing field after exiting foreach

Asked

Viewed 80 times

2

I have an object array I want to add a field in each item I do a foreach for this, but the field disappears after exiting the loop

foreach ($this->questions as $question) {
           var_dump($question); // aqui é apresentado o array no estado comum
           $question['survey_id'] = $survey_id;
           var_dump($question); // após a adesão de um novo campo o array se modifica mostrando o campo adicionado
}
// mas aqui ele volta para seu estado natural
var_dump($this->questions);

Why does this happen?

  • $question is different from $questions. For a better understanding of the problem, specify the values present in $questions and type of value you want to add to it.

2 answers

3


First, the $Question variable is only temporary and has no connection to the $questions variable. You could try passing it as a reference, I believe in this case you can do what you want.

foreach ($this->questions as &$question) {

       $question['survey_id'] = $survey_id;

}

var_dump($this->questions);

See if this way up to your need.

  • Wow it worked! so it’s like a pointer

  • Making an analogy, that would be it.

0

try like this:


foreach ($this->questions as $question) {
           var_dump($question); // aqui é apresentado o array no estado comum
           $this->questions['survey_id'] = $survey_id;
           var_dump($question); // após a adesão de um novo campo o array se modifica mostrando o campo adicionado
}
// mas aqui ele volta para seu estado natural
var_dump($this->questions);


ou


foreach ($this->questions as $question) {
           var_dump($question); // aqui é apresentado o array no estado comum
           $this->questions['survey_id'] = $survey_id;
           var_dump($question); // após a adesão de um novo campo o array se modifica mostrando o campo adicionado
}
// mas aqui ele volta para seu estado natural
var_dump($question);

  • $question is not defined outside the block foreach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.