Undermine2k
Undermine2k

Reputation: 1491

Appending to an associative array PHP

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;
}

Upvotes: 1

Views: 532

Answers (4)

Bad Wolf
Bad Wolf

Reputation: 8349

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';
}

Upvotes: 3

Axel
Axel

Reputation: 10772

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;

}

Upvotes: 3

tigrang
tigrang

Reputation: 6767

Pass a reference instead of value by using &$child

foreach($child_participants as &$child)

Upvotes: 4

Barmar
Barmar

Reputation: 782785

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.

Upvotes: 4

Related Questions