3

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.

TMH
  • 6,096
  • 7
  • 51
  • 88
  • 1
    Why not just use `$array['one'] = 'def'` and then use some `sort` - custom or native. – u_mulder Jul 02 '14 at 14:56
  • I don't think you can, but writing a custom function to do so shouldn't be that much of a problem, or is it? – kero Jul 02 '14 at 14:57
  • That's what I might end up having to do, but the sort might be awkward, the order for my current situation would be `52,51,50,44,49,46,47,48`. – TMH Jul 02 '14 at 14:58
  • 1
    Very related: http://stackoverflow.com/a/21336407/476, http://stackoverflow.com/a/20426958/476 – deceze Jul 02 '14 at 14:59
  • The question is - what for you need it? As it associative array you probably doesn't care about keys order – Marcin Nabiałek Jul 02 '14 at 14:59
  • @Marcin It's not unreasonable to want to have *ordered, associative* arrays. – deceze Jul 02 '14 at 15:00

3 Answers3

8

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;
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
2
function array_insert (&$array, $position, $insert_array) { 
  $first_array = array_splice ($array, 0, $position); 
  $array = array_merge ($first_array, $insert_array, $array); 
} 

array_insert($test, 1, array ('one' => 'def')); 

in: http://php.net/manual/en/function.array-splice.php

Linesofcode
  • 5,327
  • 13
  • 62
  • 116
0

You need to do that manually:

# Insert at offset 2

$offset = 2;
$newArray = array_slice($test, 0, $offset, true) +
            array('yourIndex' => 'def') +
            array_slice($test, $offset, NULL, true);
orif
  • 362
  • 1
  • 4
  • 15