Modifying Array Values in a Foreach Loop
In PHP, you often work with arrays of objects and want to perform operations on each object during a foreach loop. One common task is to fetch additional data for each object and update its properties.
Is it Possible to Modify Objects in a Foreach Loop?
Yes, you can modify the current object inside a foreach loop. There are two approaches:
1. Using Array Key Preservation:
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 original $questions array.
2. Using Reference Assignment:
foreach($questions as &$question){
Adding & before $question creates a reference assignment. This means that any changes made to $question within the loop will be reflected in the original $questions array.
Which Approach is Recommended?
While the reference assignment approach is more concise, it's generally recommended to use the array key preservation method. This is because it provides explicit control over which array elements are modified.
The above is the detailed content of Can You Modify Array Objects Within a PHP Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!