Edward Edward - 1 month ago 16
PHP Question

How to efficiently insert elements after another known (by key or pointer) element in a PHP array?

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~

Answer

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) + 1;

$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));