1

If I have an array like this:

$data[0] = ['a' => 'b'];
$data[1] = ['c' => 'd'];
$data[2] = ['e' => 'f'];

How do I add further data inside a specific key of the array whilst keeping the existing data, e.g.

$data[0] = ['a' => 'b'];
$data[1] = ['c' => 'd', 'xx' => 'zz']; // New data has been added here.
$data[2] = ['e' => 'f'];

How do I add things to $data[1] for example?

I've read the following but these don't seem to be the answer:

I've looked at methods like array_combine(), array_push() and array_merge() but cannot seem to do this. Apologies if this is an obvious question but I have tried to look up the things above and can't figure it out.

4

2 Answers 2

4

One way to doing it is this:

$data[1]['xx'] = 'zz';

Here is another one:

$data[1] += ['xx' => 'zz'];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works perfectly. For some reason I was looking into array_ methods which are probably not even required.
Happy to help. If this solved your question, please consider marking as answer to close this question. TY
0

you can do it by simple foreach just pass array by reference using & in foreach

$data[0] = ['a' => 'b'];
$data[1] = ['c' => 'd'];
$data[2] = ['e' => 'f'];


foreach($data as $k => &$n){

if($k == 1) $n['xx'] = 'zz';

}
print_r($data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.