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.

Andy
  • 4,326
  • 4
  • 36
  • 92
  • this one should work, no? https://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php – Erik Kalkoken Feb 02 '18 at 15:14
  • No it doesn't. `array_splice($data, 1, 0, ['xx'=>'zz']);`? – Andy Feb 02 '18 at 15:17
  • 1
    You posted links to some opinions you have found on [so]. But have you read the [documentation](http://php.net/manual/en/language.types.array.php)? Your problem is described in the ["Accessing array elements with square bracket syntax"](http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing) and ["Creating/modifying with square bracket syntax"](http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying) sections. – axiac Feb 02 '18 at 15:17
  • Please post some of your code to see how you are doing it then we can suggest you where it went wrong.. – Pankaj Feb 02 '18 at 15:20

2 Answers2

3

One way to doing it is this:

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

Here is another one:

$data[1] += ['xx' => 'zz'];
Erik Kalkoken
  • 23,798
  • 6
  • 53
  • 81
  • Thanks, that works perfectly. For some reason I was looking into `array_` methods which are probably not even required. – Andy Feb 02 '18 at 15:19
  • Happy to help. If this solved your question, please consider marking as answer to close this question. TY – Erik Kalkoken Feb 02 '18 at 15:51
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);
Arun Kumaresh
  • 5,734
  • 5
  • 28
  • 45