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~
New item in an array can be inserted with the help of array_splice() function of PHP. This function removes a portion of an array and replaces it with something else. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset.
The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
The next() function moves the internal pointer to, and outputs, the next element in the array. Related methods: prev() - moves the internal pointer to, and outputs, the previous element in the array. current() - returns the value of the current element in an array.
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));
I found a great answer here that works really well. I want to document it, so others on SO can find it easily:
/*
* Inserts a new key/value before the key in the array.
*
* @param $key
* The key to insert before.
* @param $array
* An array to insert in to.
* @param $new_key
* The key to insert.
* @param $new_value
* An value to insert.
*
* @return
* The new array if the key exists, FALSE otherwise.
*
* @see array_insert_after()
*/
function array_insert_before($key, array &$array, $new_key, $new_value) {
if (array_key_exists($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
if ($k === $key) {
$new[$new_key] = $new_value;
}
$new[$k] = $value;
}
return $new;
}
return FALSE;
}
/*
* Inserts a new key/value after the key in the array.
*
* @param $key
* The key to insert after.
* @param $array
* An array to insert in to.
* @param $new_key
* The key to insert.
* @param $new_value
* An value to insert.
*
* @return
* The new array if the key exists, FALSE otherwise.
*
* @see array_insert_before()
*/
function array_insert_after($key, array &$array, $new_key, $new_value) {
if (array_key_exists ($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
$new[$k] = $value;
if ($k === $key) {
$new[$new_key] = $new_value;
}
}
return $new;
}
return FALSE;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With