php - Array splice with a custom key -
say have 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 output
array ( [zero] => abc [two] => ghi [three] => jkl ) array ( [zero] => abc [0] => def [two] => ghi [three] => jkl )
is there anyway can set key, instead of 0
one
? in actual code need in, position, (1 in example) , require key (one in example) dynamic.
something 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;
Comments
Post a Comment