0

Need to dynamically append a key value pair to a specific place in my array.

Starting off with:

[
'controller' => 'tasks',
'action' => 'a',
'abc' => 'xyz'
]

I'd like to end with:

[
'controller' => 'tasks',
'action' => 'a',
(int) 0 => (int) 123,
'abc' => 'xyz'
]

What would be the inline code to produce this output?

I tried the following without any success:

//array_merge($x['action'], [0=>123]); //doesn't work
//array_push($x['action'], [0=>123]); //doesn't work
//$x['action'][0] = 123; //doesn't work
//$x['action'][0] => 123; //doesn't work
//$x['action'] = [0 => 123]; //doesn't work
//array_merge($x, ['action' => [0 => 123]]); //doesn't work

Solution

With the help of @o1dskoo1, final solution used:

$i = 1;
foreach($array as $key => $value)
{
    if($key == 'action')
    {
        array_splice($customUrl, $i, 0, 123); // splice in at position $i
    }
    $i++;
}
TechFanDan
  • 3,329
  • 6
  • 46
  • 89
  • I'm a bit confused on if you want index `0` to be nested under `action` or if it's a direct child of `x` (code says `action` but your example says `x`) – Spencer May Nov 21 '22 at 16:11

1 Answers1

4

You can use array_splice:

<?php

$array = [
    'controller' => 'tasks',
    'action' => 'a',
    'abc' => 'xyz'
];

$insert = [123];
 
array_splice($array, 2, 0, $insert); // splice in at position 2

print_r($array);
o1dskoo1
  • 409
  • 2
  • 9