Insert new item in array on any position in PHP
You may find this a little more intuitive. It only requires one function call to array_splice
:
$original = array( 'a', 'b', 'c', 'd', 'e' );$inserted = array( 'x' ); // not necessarily an array, see manual quotearray_splice( $original, 3, 0, $inserted ); // splice in at position 3// $original is now a b c x d e
If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.
A function that can insert at both integer and string positions:
/** * @param array $array * @param int|string $position * @param mixed $insert */function array_insert(&$array, $position, $insert){ if (is_int($position)) { array_splice($array, $position, 0, $insert); } else { $pos = array_search($position, array_keys($array)); $array = array_merge( array_slice($array, 0, $pos), $insert, array_slice($array, $pos) ); }}
Integer usage:
$arr = ["one", "two", "three"];array_insert( $arr, 1, "one-half");// ->array ( 0 => 'one', 1 => 'one-half', 2 => 'two', 3 => 'three',)
String Usage:
$arr = [ "name" => [ "type" => "string", "maxlength" => "30", ], "email" => [ "type" => "email", "maxlength" => "150", ],];array_insert( $arr, "email", [ "phone" => [ "type" => "string", "format" => "phone", ], ]);// ->array ( 'name' => array ( 'type' => 'string', 'maxlength' => '30', ), 'phone' => array ( 'type' => 'string', 'format' => 'phone', ), 'email' => array ( 'type' => 'email', 'maxlength' => '150', ),)