Home > Backend Development > PHP Tutorial > How Can I Modify Array Objects During a Non-Destructive Foreach Loop in PHP?

How Can I Modify Array Objects During a Non-Destructive Foreach Loop in PHP?

Barbara Streisand
Release: 2024-12-15 03:20:09
Original
593 people have browsed it

How Can I Modify Array Objects During a Non-Destructive Foreach Loop in PHP?

Non-Destructive Loop Iteration with Modified Object Values

When iterating through an array using a foreach loop, it may be desirable to modify the current object being handled within the loop. This can be achieved using two approaches.

Approach 1: Using Array Key Preserving

To preserve the key of the current object, use the following syntax:

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

Here, the key ($key) is saved and used to update the corresponding value in the main $questions variable.

Approach 2: Using Reference Assignment

Alternatively, adding the & to the foreach loop value will update the $questions variable directly:

foreach($questions as &$question){
Copy after login

This approach modifies the value by reference, keeping the $questions array updated. However, the first approach is generally recommended.

PHP Documentation Note:

According to the PHP foreach documentation:

"In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference."

The above is the detailed content of How Can I Modify Array Objects During a Non-Destructive Foreach Loop in PHP?. 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