Home > Backend Development > PHP Tutorial > How to Modify Array Values in a PHP Foreach Loop: Reference or Key?

How to Modify Array Values in a PHP Foreach Loop: Reference or Key?

Linda Hamilton
Release: 2024-12-12 17:29:10
Original
134 people have browsed it

How to Modify Array Values in a PHP Foreach Loop: Reference or Key?

Modifying Array Values within a Foreach Loop

In PHP, it is possible to modify the current object being handled within a foreach loop. To do so, there are two primary approaches:

Using a Loop Variable with Array Key:

<?php
foreach($questions as $key => $question){
    $questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
?>
Copy after login

Here, we iterate over the $questions array using a loop variable ($key) that represents the array index. By explicitly updating the $questions array at the corresponding index ($key), we effectively modify the original object.

Using a Reference:

<?php
foreach($questions as &$question){
    $question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
?>
Copy after login

In this case, we add an ampersand (&) before the loop variable ($question), which passes a reference to the object. By modifying the object through the reference, we directly update the object in the original $questions array.

Which Approach is Recommended?

While both approaches work, using a loop variable with array key is generally preferred. This is because it explicitly updates the original array, making it easier to track modifications for debugging or further processing.

The above is the detailed content of How to Modify Array Values in a PHP Foreach Loop: Reference or Key?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template