Sometimes, we want to modify array values in foreach loop with PHP.
In this article, we’ll look at how to modify array values in foreach loop with PHP.
How to modify array values in foreach loop with PHP?
To modify array values in foreach loop with PHP, we can get value by the key to assign a new value to it.
For instance, we write
<?php
foreach ($questions as $key => $question) {
$questions[$key]["answers"] = $answers_model->get_answers_by_question_id(
$question["question_id"]
);
}
to use the foreach loop to loop through the key-value pairs in $questions
.
Then we assign $questions[$key]["answers"]
to a new value in the loop.
Conclusion
To modify array values in foreach loop with PHP, we can get value by the key to assign a new value to it.