Question:
Is it possible to edit the current object being handled within a foreach loop?
Context:
You have an array of objects ($questions) with associated answers in a database. You're attempting to fetch these answers for each question object during the loop iteration.
Solution:
You can modify the current object within a foreach loop by using one of the following methods:
Key Assignment:
foreach($questions as $key => $question){ $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']); }
This method preserves the array key, allowing you to update the value directly.
Reference Assignment:
foreach($questions as &$question){ $question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']); }
Adding an ampersand (&) before the variable name passes the reference to the object, enabling direct modifications within the loop.
Recommendation:
While the reference assignment method is concise, the key assignment method is generally recommended as it ensures predictable behavior in multidimensional arrays.
The above is the detailed content of Can I Modify Array Objects Directly Within a Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!