Modify array values in foreach loop

Modify array values in foreach loop

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Modifying Array Values Inside a foreach Loop

In PHP, you can absolutely modify the value of an element within a foreach loop by directly assigning to that element's key. This capability is particularly useful when you are fetching related data from a database and wish to hydrate the objects in place before rendering them. Your specific use case involves iterating over a collection of questions, querying for associated answers, and attaching those results to the question object itself.

The code snippet you provided demonstrates this pattern effectively:

foreach ($questions as $question) {
    // Fetch answers based on the current question's ID
    $answers = $answers_model->get_answers_by_question_id($question['question_id']);
    
    // Directly assign the result to the current element
    $question['answers'] = $answers;
}

In this example, the variable $question represents a reference to the specific array element currently being iterated. When you execute $question['answers'] = $answers, you are not creating a local copy of the data; you are updating the property of the actual element residing in the $questions array. Once the loop finishes, every item in the original $questions array will contain the answers key populated with the fetched data.

This approach relies on PHP's value semantics regarding the iteration variable. When you use foreach ($array as $value), the variable $value is initialized to the current element of $array. For scalar types like strings or integers, modifying $value has no effect on the array because PHP copies the value at the start of each iteration. However, when the element is an array or an object, you can mutate it if you assign a new value to a key within that structure using syntax like $value['new_key'] = 'data'.

There are two primary ways to handle this mutation, and understanding the distinction prevents common bugs. The first method is direct assignment to the array index, as shown above. This works seamlessly with associative arrays where you simply add or overwrite keys. The second method involves using references, which is necessary if you want to change the variable itself (e.g., changing the whole object) rather than just a property of it.

foreach ($questions as &$question) {
    $question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
unset($question); // Crucial: break the reference after the loop

While direct assignment to keys is often sufficient, using a reference (&$question) allows you to mutate the entire object if needed. However, it introduces a significant pitfall: the reference persists after the loop ends, pointing to the last element processed. Failing to unset $question or break the reference can lead to unexpected behavior in subsequent code that relies on $question being cleared or nullified.

Performance considerations also apply here. If the number of questions is massive and the database queries inside the loop are expensive, you might hit latency issues. In such scenarios, fetching all data in a single query using Eloquent relationships (e.g., Question::with('answers')->get()) is often superior to executing N+1 queries via a manual loop. This is a classic optimization pattern in Laravel where eager loading prevents the performance degradation associated with multiple round-trips to the database.

If you are working within the Laravel ecosystem, ensure that your models and relationships are configured correctly to support this hydration strategy. The with method allows you to load the related data efficiently before entering your logic loop. For instance:

$questions = Question::with('answers')->get();

foreach ($questions as $question) {
    // Now $question->answers is already populated if using Eloquent models
    // No need for manual fetching inside the loop unless custom logic is required
}

However, if you are using a custom model method like $answers_model->get_answers_by_question_id, sticking to the direct assignment pattern within your loop remains valid and straightforward. Just remember that modifying the array element in place ensures that any subsequent operations on $questions will see the updated state immediately.

Our network