Insert new item in array on any position in PHP

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

How can I insert a new item into an array on any position, for example in the middle of array?

回答1:

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  array_splice( $original, 3, 0, $inserted ); // splice in at position 3 // $original is now a b c x d e 


回答2:

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',   ), ) 


回答3:

$a = array(1, 2, 3, 4); $b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2)); // $b = array(1, 2, 5, 3, 4) 


回答4:

This way you can insert arrays:

function array_insert(&$array, $value, $index) {     return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array); } 


回答5:

There is no native PHP function (that I am aware of) that can do exactly what you requested.

I've written 2 methods that I believe are fit for purpose:

function insertBefore($input, $index, $element) {     if (!array_key_exists($index, $input)) {         throw new Exception("Index not found");     }     $tmpArray = array();     $originalIndex = 0;     foreach ($input as $key => $value) {         if ($key === $index) {             $tmpArray[] = $element;             break;         }         $tmpArray[$key] = $value;         $originalIndex++;     }     array_splice($input, 0, $originalIndex, $tmpArray);     return $input; }  function insertAfter($input, $index, $element) {     if (!array_key_exists($index, $input)) {         throw new Exception("Index not found");     }     $tmpArray = array();     $originalIndex = 0;     foreach ($input as $key => $value) {         $tmpArray[$key] = $value;         $originalIndex++;         if ($key === $index) {             $tmpArray[] = $element;             break;         }     }     array_splice($input, 0, $originalIndex, $tmpArray);     return $input; } 

While faster and probably more memory efficient, this is only really suitable where it is not necessary to maintain the keys of the array.

If you do need to maintain keys, the following would be more suitable;

function insertBefore($input, $index, $newKey, $element) {     if (!array_key_exists($index, $input)) {         throw new Exception("Index not found");     }     $tmpArray = array();     foreach ($input as $key => $value) {         if ($key === $index) {             $tmpArray[$newKey] = $element;         }         $tmpArray[$key] = $value;     }     return $input; }  function insertAfter($input, $index, $newKey, $element) {     if (!array_key_exists($index, $input)) {         throw new Exception("Index not found");     }     $tmpArray = array();     foreach ($input as $key => $value) {         $tmpArray[$key] = $value;         if ($key === $index) {             $tmpArray[$newKey] = $element;         }     }     return $tmpArray; } 


回答6:

function insert(&$arr, $value, $index){            $lengh = count($arr);     if($index$lengh)         return;      for($i=$lengh; $i>$index; $i--){         $arr[$i] = $arr[$i-1];     }      $arr[$index] = $value; } 


回答7:

This is also a working solution:

function array_insert(&$array,$element,$position=null) {   if (count($array) == 0) {     $array[] = $element;   }   elseif (is_numeric($position) && $position $element),$part2);     foreach($array as $key=>$item) {       if (is_null($item)) {         unset($array[$key]);       }     }   }   elseif (is_null($position)) {     $array[] = $element;   }     elseif (!isset($array[$position])) {     $array[$position] = $element;   }   $array = array_merge($array);   return $array; } 

credits go to: http://binarykitten.com/php/52-php-insert-element-and-shift.html



回答8:

Based on @Halil great answer, here is simple function how to insert new element after a specific key, while preserving integer keys:

private function arrayInsertAfterKey($array, $afterKey, $key, $value){     $pos   = array_search($afterKey, array_keys($array));      return array_merge(         array_slice($array, 0, $pos, $preserve_keys = true),         array($key=>$value),         array_slice($array, $pos, $preserve_keys = true)     ); }  


回答9:

You can use this

foreach ($array as $key => $value)  {     if($key==1)     {         $new_array[]=$other_array;     }        $new_array[]=$value;     } 


回答10:

Normally, with scalar values:

$elements = array('foo', ...); array_splice($array, $position, $length, $elements); 

To insert a single array element into your array don't forget to wrap the array in an array (as it was a scalar value!):

$element = array('key1'=>'value1'); $elements = array($element); array_splice($array, $position, $length, $elements); 

otherwise all the keys of the array will be added piece by piece.



回答11:

Hint for adding an element at the beginning of an array:

$a = array('first', 'second'); $a[-1] = 'i am the new first element'; 

then:

foreach($a as $aelem)     echo $a . ' '; //returns first, second, i am... 

but:

for ($i = -1; $i 


回答12:

if unsure, then DONT USE THESE:

$arr1 = $arr1 + $arr2; 

OR

$arr1 += $arr2; 

because with + original array will be overwritten. (see source)



回答13:

Try this one:

$colors = array('red', 'blue', 'yellow');  $colors = insertElementToArray($colors, 'green', 2);   function insertElementToArray($arr = array(), $element = null, $index = 0) {     if ($element == null) {         return $arr;     }      $arrLength = count($arr);     $j = $arrLength - 1;      while ($j >= $index) {         $arr[$j+1] = $arr[$j];         $j--;     }      $arr[$index] = $element;      return $arr; } 


回答14:

Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.

$original = ( [0] => Array     (         [title] => Speed         [width] => 14     )  [1] => Array     (         [title] => Date         [width] => 18     )  [2] => Array     (         [title] => Pineapple         [width] => 30      ) ) 

Adding an item in same format to this array will add all new array indexes as items instead of just item.

$new = array(     'title' => 'Time',     'width' => 10 ); array_splice($original,1,0,array('random_string')); // can be more items $original[1] = $new;  // replaced with actual item 

Note: Adding items directly to a multidimensional array with array_splice will add all its indexes as items instead of just that item.



回答15:

For inserting elements into an array with string keys you can do something like this:

/* insert an element after given array key  * $src = array()  array to work with  * $ins = array() to insert in key=>array format  * $pos = key that $ins will be inserted after  */  function array_insert_string_keys($src,$ins,$pos) {      $counter=1;     foreach($src as $key=>$s){         if($key==$pos){             break;         }         $counter++;     }       $array_head = array_slice($src,0,$counter);     $array_tail = array_slice($src,$counter);      $src = array_merge($array_head, $ins);     $src = array_merge($src, $array_tail);      return($src);  }  


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!