Steve
Steve

Reputation: 117

How to update an element within an array which is in an array itself?

$array['11'][] = [
   'One' => True,
   'Two' => False
];

How would I update the key-value of 'Two'? I've tried array_replace() with

$new_array['11'][] = [
   'Two' => True
];

But that does replaces the entire $array with $new_array. Meaning it'll become

$array['11'][] = [
    'Two' => False
];

Upvotes: 0

Views: 39

Answers (2)

samsungcruiser
samsungcruiser

Reputation: 16

You actually have a 3 dimensional array therefore you need to properly reference the value of the child element you want to update.

$array['11'][0]['Two'] = True;

This should do it.

Upvotes: 0

Barmar
Barmar

Reputation: 780673

There's no built-in function to do this, you need to loop over the array.

foreach ($array['11'] as &$subarray) {
    $subarray['Two'] = true;
}

The & makes $subarray a reference so modifying it updates the original array.

Upvotes: 1

Related Questions