phparraysarray-splice

Insert a new associative element into an associative array and preserve keys


Say I have this code

$test = array();
$test['zero'] = 'abc';
$test['two'] = 'ghi';
$test['three'] = 'jkl';
dump($test);

array_splice($test, 1, 0, 'def');

dump($test);

Which gives me the output

Array
(
    [zero] => abc
    [two] => ghi
    [three] => jkl
)

Array
(
    [zero] => abc
    [0] => def
    [two] => ghi
    [three] => jkl
)

Is there anyway I can set the key, so instead of 0 it could be one? In the actual code I need this in, the position, (1 in this example) and the require key (one in this example) will be dynamic.


Solution

  • Something like this:

    $test = array_merge(array_slice($test, 0, 1),
                        array('one'=>'def'),
                        array_slice($test, 1, count($test)-1));
    

    Or shorter:

    $test = array_merge(array_splice($test, 0, 1), array('one'=>'def'), $test);
    

    Even shorter:

    $test = array_splice($test, 0, 1) + array('one'=>'def') + $test;
    

    For PHP >= 5.4.0:

    $test = array_splice($test, 0, 1) + ['one'=>'def'] + $test;