Home > Enterprise >  Appending key value pair to existing array key
Appending key value pair to existing array key

Time:11-22

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

CodePudding user response:

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);
  •  Tags:  
  • php
  • Related