Edward Edward - 1 year ago 92
PHP Question

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

Given an array:

$a = array(

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 Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download