PHP array_insert_after() & array_insert_before()
I need to insert a key/value at a certain position in an associative array. It seems like a common issue. I was surprised to discover there wasn’t a straightforward answer. Here is the method I created. If you know of a more efficient method, please let me know in the comments.
I located: http://stackoverflow.com/questions/1286853/how-to-efficiently-insert-elements-after-another-known-by-key-or-pointer-eleme The number of array_*
function calls in the selected answer must be inefficient.
/*
* 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;
}
Comments
(Statically copied from previous site)
Alex replied on August 14, 2013 - 5:25am
Very nice. Exactly what i was looking for. Thanks
Jacek replied on November 18, 2014 - 5:27pm
Thx a lot, working perfect in my CMS
l0l replied on April 11, 2017 - 1:18pm
thanks bro
Supekozel replied on September 29, 2019 - 8:35pm
There is mistake in code. $array = $new; INSTEAD of return $new;