1

I must be missing something obvious: I'm returning an associative array after my query runs, and for each nested array I wish to append $child['Is_Child'] = '0'; When I print out the $child array it is correct, but the $child_participants array does not have it appended; why?

if ($query->num_rows() > 0)
{
    $child_participants = $query->result_array();
    foreach($child_participants as $child)
    {
        $child['Is_Child'] = '0';
    }

    return $child_participants;
}

4 Answers 4

4

Pass a reference instead of value by using &$child

foreach($child_participants as &$child)
Sign up to request clarification or add additional context in comments.

Comments

4

By default, $child is a copy of the element of the original array. You need to use a reference to modify the actual element:

foreach ($child_participants as &$child) {
    $child['Is_Child'] = '0';
}

The & operator makes this a reference.

Comments

3

Because you are modifying $child as it's called, not the parent array.

You can do this:

if ($query->num_rows() > 0)
{
   $child_participants= $query->result_array();
   foreach($child_participants as $key => $child) 
    {
        $child_participants[$key]["Is_Child"] = '0'; ;
    }

   return $child_participants;

}

Comments

3

The $child variable, as you declared it in a PHP foreach array, is immutable unless you tell PHP to make it mutable with the & operator.

foreach($child_participants as &$child)
{
    $child['Is_Child'] = '0';
}

1 Comment

It's mutable, it's just not the same as the element of the original array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.