views:

209

answers:

4

Given an array:

$a = array(
    'abc',
    123,
    'k1'=>'v1',
    'k2'=>'v2',
    78,
    'tt',
    'k3'=>'v3'
);

With its internal pointer on one of its elements, how do I insert an element after the current element? And how do I insert an element after a key-known element, say 'k1'?

Performance Care~

+1  A: 

You can't use internal array pointer to insert elements.

There's array_splice which can insert/remove/replace elements and subarrays, but it's intended for integer-indexed arrays.

I'm afraid you'll have to rebuild the array to insert element (except cases where you want to insert first/last element) or use separate integer-indexed array for holding keys in the order you want.

porneL
A: 

This way is fine for new values without keys. You can not insert value with a key, and numeric indexes will be 'reset' as 0 to N-1.

$keys = array_keys($a);
$index = array_flip($keys);

$key = key($a); //current element
//or 
$key = 'k1';

array_splice($a, $index[$key] + 1, 0, array('value'));
OIS
A: 

Generally speaking doubly linked list would be ideal for this task.

There even is a implementation of that since PHP 5.3, called SplDoublyLinkedList, but sadly this one is currently missing methods to add/remove nodes from/to somewhere in the middle.

So, for now you have to resort to array splicing.

Anti Veeranna
+1  A: 

You could do it by splitting your array using array_keys and array_values, then splice them both, then combine them again.

$insertKey = 'k1';

$keys = array_keys($arr);
$vals = array_values($arr);

$insertAfter = array_search($insertKey, $keys);

$keys2 = array_splice($keys, $insertAfter);
$vals2 = array_splice($vals, $insertAfter);

$keys[] = "myNewKey";
$vals[] = "myNewValue";

$newArray = array_merge(array_combine($keys, $vals), array_combine($keys2, $vals2));
nickf