Viewed   223 times

I was wondering if it is possible to edit the current object that's being handled within a foreach loop

I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.

foreach($questions as $question){
    $question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);



There are 2 ways of doing this

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

This way you save the key, so you can update it again in the main $questions variable


foreach($questions as &$question){

Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)

Per 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.

Sunday, September 25, 2022

If you want to loop continually you can use

$infinate = new InfiniteIterator(new ArrayIterator($array));
foreach ( $infinate as $value ) {

    // Do your thing
    // Remember to break

Sunday, November 27, 2022
            foreach ($item['criteria'] as $item2){
             echo '<a href="javascript:toggle('. $item2['id']. ')">Click</a>';
             echo '<div id="'. $item2['id'].'" style="display: none">'. $item2['description'].'</div>';


you have some syntactical mistakes check this once

Saturday, October 29, 2022

If you're using PHP 5.5+, you can use array_column(), like so:

$result = array_column($foo, 'type');

If you want an array with numeric indices, use:

$result = array_values(array_column($foo, 'type'));

If you're using a previous PHP version and can't upgrade at the moment, you can use the Userland implementation of array_column() function written by the same author.

Alternatively, you could also use array_map(). This is basically the same as a loop except that the looping is not explicitly shown.

$result = array_map(function($arr) {
   return $arr['type'];
}, $foo);
Wednesday, October 12, 2022

foreach works with a copy of $item, so you cannot modify your original array inside the foreach. One way to work around this is to use the & operator.

foreach($array as &$item) {
    if (is_array($item)) {
        $item['key3'] = 'val3';

Another, more elegant way would be to use array_walk():

array_walk($array, function (&$v, $k) { 
    if (is_array($v)) {
        $v['key3'] = 'val3';

This example will work from PHP 5.3, where Closures were introduced.

Saturday, October 1, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :