Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Array Functions : array_splice

array_splice

Remove a portion of the array and replace it with something else (PHP 4, PHP 5)
array array_splice ( array &input, int offset [, int length [, array replacement]] )

array_splice() removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. It returns an array containing the extracted elements. Note that numeric keys in input are not preserved.

If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.

If replacement array is specified, then the removed elements are replaced with elements from this array. 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. Note that keys in replacement array are not preserved. If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.

The following statements change the values of $input the same way:

Tableá21.áarray_splice() equivalents

array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y))
array_pop($input) array_splice($input, -1)
array_shift($input) array_splice($input, 0, 1)
array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y))
$input[$x] = $y // for arrays where key equals offset array_splice($input, $x, 1, $y)


Returns the array consisting of removed elements.

Exampleá278.áarray_splice() examples

<?php
$input
= array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
// á á á á á"blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
// á á á á á"blue", "purple", "yellow");
?>


See also array_slice(), unset(), and array_merge().

Related Examples ( Source code ) » array_splice


Code Examples / Notes » array_splice

kbrown

[ Editor's Note: If you're not concerned with the indexes being contiguously numbered (such as for an associative array) then unset($ar[$ind]); will accomplish the same as the code below without requiring splice/splice/merge.  If contiguous numbering IS a concern (such as for indexed arrays), you can still save time by using: unset($ar[$ind]); $ar = array_values($ar); ]
Removing elements from arrays
This works better - much quicker
<?php
$ar = array("einstein", "bert", "colin", "descartes", "renoir");
$a = array_slice($ar, 0, $ind);
$b = array_slice($ar, $ind + 1);
$ar = array_merge($a, $b);
?>


weikard

You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".
[DATA]
$test_array = array (
 row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
 row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
 row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);
[ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
[RESULT]
Array (
   [row1] => Array (
           [col1] => foobar!
           [col2] => foobar!
       )
   [row2] => Array (
           [col1] => foobar!
           [col2] => foobar!
       )
   [0] => Array (
           [colX] => foobar2
       )
   [row3] => Array (
           [col1] => foobar!
           [col2] => foobar!
       )
)
But you can use the following function:
function array_insert (&$array, $position, $insert_array) {
 $first_array = array_splice ($array, 0, $position);
 $array = array_merge ($first_array, $insert_array, $array);
}
[ACTION]
array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
[RESULT]
Array (
   [row1] => Array (
           [col1] => foobar!
           [col2] => foobar!
       )
   [row2] => Array (
           [col1] => foobar!
           [col2] => foobar!
       )
   [rowX] => Array (
           [colX] => foobar2
       )
   [row3] => Array (
           [col1] => foobar!
           [col2] => foobar!
       )
)
[NOTE]
The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.


michael

While trying to find a way to insert some array into another at some index, array_splice seemed like the function that I wanted. The results weren't quite as expected though. Of course, I can be using it wrong.
My desired results turned out be $array1 after calling array_splice() and no tuning got me to have $array3 with what was showing up in $array1.
[code]
<?php
       $array1                 = array(1, 2, 3, 7, 8, 9);
       $array2                 = array(4, 5, 6);
       echo '<br />array1 :: ';
       print_r( $array1 );
       echo '<br />array2 :: ';
       print_r( $array2 );
       $index                  = 3;
       // $length                  = count($array1);
       // $length                  = -1;
       $length                 = 0;
       // array1 is call by reference it seems
       $array3                 = array_splice($array1, $index, $length,
                                   $array2);
       echo '<br />array1 :: ';
       print_r( $array1 );
       echo '<br />array2 :: ';
       print_r( $array2 );
       echo '<br />array3 :: ';
       print_r( $array3 );
?>
[/code]
Results in
[code]
array1 :: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 7 [4] => 8 [5] => 9 )
array2 :: Array ( [0] => 4 [1] => 5 [2] => 6 )
array1 :: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )
array2 :: Array ( [0] => 4 [1] => 5 [2] => 6 )
array3 :: Array ( )
[/code]
Cheers,
Michael


ajd

weikard's function below is useful but it will still strip keys from array elements where the key is an integer, whether or not it is in a string:
<?php
function array_insert (&$array, $position, $insert_array) {
 $first_array = array_splice ($array, 0, $position);
 $array = array_merge ($first_array, $insert_array, $array);
}
$f = array("three" => "zzz", "3" => "yyy");
$a = array("4.0" => "zzzz", "four" => "yyyy");
array_insert($a,0,$f);
var_dump($a);
// array(4) { ["three"]=> string(3) "zzz" [0]=> string(3) "yyy"  ["4.0"]=> string(4) "zzzz" ["four"]=> string(4) "yyyy" }
?>


18-aug-2003 11:57

Want to insert a new value in the middle of the array, without overwriting other elements? Try this.
<?php
$array = array(
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5
);
array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3)));
echo '<pre>';
print_r($array);
?>
Output:
Array
(
   [0] => 0
   [1] => 1
   [2] => 2
   [3] => x
   [4] => 3
   [5] => 4
   [6] => 5
)
As you can see, the operation add 'X' in the 4th place, pushing everything else to the next key.


steve

Values removed from the array are returned as an array as such:
<?php
$letters = array("a","b","c");
$removed_val = array_splice($letters, 1, 1);
print_r($removed_val);
?>
Printed Result:
Array ( [0] => b )


randomdestination

To split an associative array based on it's keys, use this function:
<?php
function &array_split(&$in) {
$keys = func_get_args();
array_shift($keys);

$out = array();
foreach($keys as $key) {
if(isset($in[$key]))
$out[$key] = $in[$key];
else
$out[$key] = null;
unset($in[$key]);
}

return $out;
}
?>
Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');
print_r($testin);
print_r($testout);
?>
Will print:
Array
(
   [d] => 4
)
Array
(
   [a] => 1
   [b] => 2
   [c] => 3
)
Hope this helps anyone!


kokos

To paule@cs.tamu.edu :
Sorry, but the fix will still not work properly - when $length=0 (e.g. trying to insert one value) the
  $new_array[$key]=$replacement;
would be immediately followed by
  $new_array[$key]=$value;
and the $replacement will be lost.
What i was trying to point out in my original post is that $input[$x]=$y is NOT equivalent to array_splice($input, $x, 1, $y) . The equivalence mentioned would be true ONLY when $input is <... ghmm... > "automatically enumerated", having its' keys exactly matching offsets of corresponding elements in the array. But, in general case, keys do not match offsets - perhaps this should be explicitly stated in the Description above.


paule

to kokos@lac.lviv.ua:
Good point about the code not doing what you expected.
The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.


cronodragon_at_gmail

To delete an element of an array just use unset(). Example:
// Deletes the element with the key "quux" from array $bar
unset($bar['quux']);
Easy! =)


jtgt

This function will preserve keys:
<?php
function my_array_splice(&$_arr, $_index, $_long){
  $_keys=array_keys($_arr);
  $_key=array_search($_index, $_keys);
  if ( $_key !== FALSE ){
  $_keys=array_splice($_keys, $_key, $_long);
  foreach ($_keys as $_key) unset($_arr[$_key]);
  }
}
?>


amtiee

The function my_array_splice(), accepts a user defined key of an array.
$aArray ={'Name'=>'ABC','Age'=>'22', 'Sex'=>'M'};
my_array_splice($aArray, 'Age', 1);
So now $aArray will contain only:
['Name'=>'ABC', 'Sex'=>'M']
my_array_splice() internally makes use of array_search(), which is not supported with PHP <= 4.0.4. A solution to this is to sneak into user contributed notes of function array_search(). An alternative submitted by chen.avinadav@vbulletin.com is the solution for this problem.


bdjumakov

Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.
<?php
function array_move($which, $where, $array)
{
$tmp  = array_splice($array, $which, 1);
array_splice($array, $where, 0, $tmp);
return $array;
}
?>


19-jun-2002 03:14

Please note that array_splice() 's second argument is an OFFSET and not an INDEX.
Lets say you want to
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */
Now, lets say we want to remove that "myitem" from the array:
<?php
$array_of_items = array_splice($array_of_items,(1+$sid),1);
?>
Notice how you have to add a one to the $sid variable?  That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
its OFFSET.
DO NOT DO THIS:
$array_of_items = array_splice($array_of_items,$sid,1);


brissaille

Pay attention, if the keys of your
array are integer, array_splice will
modify them.
For example:
$t=array('5'=>'Albator', '7'=>'Goldorak', 21=>'Candy');
array_splice($t,0,0) gives you the follwing result:
$t=array {[0]=>'Albator', [1]=>'Goldorak', [2]=>'Candy'}


info

note that unset() works well for associative arrays, but if you have
$blah = array("a","b","c","d");
and you unset($blah[2]), then the other
elements will not shift, i.e., you'll still have $blah[0], $blah[1], and $blah[3].  If you need things to shift, use
array_splice($blah,2,1);


richard

My function can remove it by its name or if its equal to something. Became useful because I was inserting all the stuff from the post array into the database but the damn submit button kept comming up with the $_POST also so I wrote this function to get rid of it.
-------------------------------------
<?
/*
func.array_slice2.php

Removes a slice from an array given the name of
it or the value

Ex:
$array=array_slice2($_POST, "submit_button");
*/
function array_slice2($array, $val, $slice="name"){
switch($slice){
case "name":
while(list($i)=each($array)){
if($i!=$val){
$return[$i]=$array[$i];
}
}
break;

case "variable":
while(list($i)=each($array)){
if($array[$i]!=$val){
$return[$i]=$array[$i];
}
}
break;
}

return $return;
}
?>


plintus

key-safe:
<?php
function array_kslice ($array, $offset, $length = 0) {
$k = array_slice (array_keys ($array), $offset, $length);
$v = array_slice (array_values ($array), $offset, $length);
for ($i = 0; $i < count ($k); $i ++) $r[$k[$i]] = $v[$i];
return $r;
}
?>
smth like this. hope you like it more than versions above :)


juan guillermo fernández

Just fenced the infamous problem of the Associative Arrays v/s array_splice.
I've done this little function to get around it. It seems to work pretty well, by I'm kind of a novice in this so I'm sure you'll find bugs, or better ways to do it:
<?php
function ass_array_splice
( $in_arr,
 $desp,
 $size,
 $sust,
 $new_key='')
{
$head=array_slice($in_arr,0,$desp);
$tale=array_slice($in_arr,$desp+$size);
if ($new_key!='')
  $arr_res=array_merge($head,
                                array($new_key=>$sust),
                                $tale);
else $arr_res=array_merge( $head,
                                     $sust,
                                     $tale);
return $arr_res;
}
?>
that's it. You call it like this:
<?php
$P=ass_array_splice($_P,
                             18,
                              3,
$P['FechD'].'/'.$P['FechM'].'/'.$P['FechA'],'Fech');
?>
this example merges three cells from the array, and replace themselves with the result, calling the new cell 'Fech'. If you omit the last param, it calls the cel '0', just like old array_splice does.
thanks for any feedback!


kokos

It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...
Contrary to the equivalence noted on this page
$input[$x] = $y   <==>   array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!
The following code:
  $t=array('a','b','c','d','e');
  var_dump($t);
<?php
  unset($t[0],$t[1],$t[3]);
  $t[0]='f';
  var_dump($t);
  array_splice($t,0,1,'g');
  var_dump($t);
?>
Will produce:
array(5) {
 [0]=>
 string(1) "a"
 [1]=>
 string(1) "b"
 [2]=>
 string(1) "c"
 [3]=>
 string(1) "d"
 [4]=>
 string(1) "e"
}
array(3) {
 [2]=>
 string(1) "c"
 [4]=>
 string(1) "e"
 [0]=>
 string(1) "f"
}
array(3) {
 [0]=>
 string(1) "g"
 [1]=>
 string(1) "e"
 [2]=>
 string(1) "f"
}
Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_.  :)
I think that "equivalence note" should be considered buggy.  ;)))
Best wishes.
KoKos.


tsunaquake doesntlikespam @ wp dot pl

It is possible to use a string instead of offset, eg if you want to deletre the entry $myArray['entry'] then you can simply do it like this:
<?php
array_splice($myArray, 'entry', 1);
?>
Note that you can use unset($myArray['entry']) as well but then, it doesn't enable you to remove more than one entry and it doesn't replace anything in the array, if that's what you intend to do.


roeltje.com

In reply on the message "18-Aug-2003 09:57"
If you want to insert a value into some array
<?
// I think we can replace
array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3)));
// with for inserting multiple values
array_splice($array, 3, 0, array('x','y'));
// or for just inserting 1 value
array_splice($array, 3, 0, 'x');
?>
Sounds to me a lot faster.
 Roeltje...


paul

In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.
In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).


julien pachet

If you want to remove an item of the array, shifting the others values, you can use:
function my_array_unset($array,$index) {
 // unset $array[$index], shifting others values
 $res=array();
 $i=0;
 foreach ($array as $item) {
   if ($i!=$index)
     $res[]=$item;
   $i++;
 }
 return $res;
}


cwahl

I couldn't get array_splice() to insert into a multidimensional array, so I cribbed this from the notes for array_push() (a thousand thanks to jhall at jadeinternet dot net).  I'm dealing with a spreadsheet-looking dataset, and it lets me add "rows" where the row data is the array that I have assigned to $val, and the row number is $ky:
<?php
function insert_into_array($array,$ky,$val)
{
$n = $ky;
foreach($array as $key => $value)
 {
   $backup_array[$key] = $array[$key];
 }
$upper_limit = count($array);
while($n <= $upper_limit)
 {
   if($n == $ky)
     {
$array[$n] = $val;
echo $n;
     }
   else
     {
$i = $n - "1";
$array[$n] = $backup_array[$i];
     }
   $n++;
 }
return $array;
}
?>
So that:
<?php
$list = array( "0" => "zero",
     "1" => "one",
     "2" => "two",
     "3" => "three",
   "4" => "four",
     "5" => "five",
     "6" => "six");
$value = "New Number Three";
$key = "3";
$new = insert_into_array($list,$key, $value);
?>
Will Return:
$list =
Array
(
  [0] => zero
  [1] => one
  [2] => two
  [3] => three
  [4] => four
  [5] => five
  [6] => six
)
$new=
Array
(
  [0] => zero
  [1] => one
  [2] => two
  [3] => New Number Three
  [4] => three
  [5] => four
  [6] => five
  [7] => six
)


paule

I believe the following is a version of array_slice that solves most of the issues for people that want an associative key offset, rather than an integer.
<?php
function key_array_splice(&$input, $key_ofs, $length=NULL, $replacement=NULL)
{
   // Adjust the length if it was negative or not passed
   if($length===NULL || $length<0)
       $count = $length+count($input);
   // Cycle through the array
   foreach($input as $key=>$value){
       if(!$key_found){
           if($key===$key_ofs){
               $key_found=true;
               if($length!==NULL && $length>=0)
                   $count=$length;
               if(is_array($replacement))
                   foreach($replacement as $r_key=>$r_value)
                       $new_array[$r_key]=$r_value;
           }else
               $new_array[$key]=$value;
       }
       if($key_found){
           if($count>0)
               $ret_array[$key]=$value;
           else
               $new_array[$key]=$value;
       }
       $count--;
   }
   // Finish up
   $input=$new_array;
   return $ret_array;
}
?>
Note that this code needs PHP 4 for the use of the "===" and "!==" operators.


saurabhmdh

for inserting array in 2-d array, according x position, y position
function add_module_xy($x_loc, $y_loc, $module) {
   //identify the column of the modules
   switch ($x_loc) {
     case 1:
       $x = 'left';
       break;
     case 2:
       $x = 'middle';
       break;
     case 3:
       $x = 'right';
       break;
     default:
       throw new Exception("", "Invalid horizontal position $x_loc");
   }
   
   $max_y_loc = count($this->module_arrays[$x]) + 1;
   if ($y_loc > $max_y_loc) {
     //if y location is greater then max array index then add module to last
     $y_loc = $max_y_loc;
   }
   $left = array_slice ($this->module_arrays[$x], 0, $y_loc-1);
   $right = array_slice ($this->module_arrays[$x], $y_loc-1);
   $insert[0] = $module;
   $array = array_merge ($left, $insert, $right);
   $this->module_arrays[$x] = $array;
   
 }


gerry-03

For anybody who is wondering... jrhardytwothousandtwo's trick for inserting an element using array_splice, will also work with multi-dimensional arrays if you do the following:
<?php
 function array_insert(&$input, $offset, $replacement){
   array_splice($input, $offset, 0, 0);
   $input[$offset] = $replacement;
 }
?>
I'm not sure if this (or a derivative of it) will solve other problems that I have seen just about everybody on here trying to solve. But apart from it's hackish nature, it works well for me.


php barryhunter co uk

Following on from weikard's function here is a slight variation that accepts a key in the associative array to insert the new array after, instead of simply an index.
<?php
function array_insert(&$array, $position, $insert_array) {
if (!is_int($position)) {
$i = 0;
foreach ($array as $key => $value) {
if ($key == $position) {
$position = $i;
break;
}
$i++;
}
}
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}
?>


mip

Ever wounder what array_splice is doing to your references, then try this little script and see the output.
<?php
$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);
$arr[0] = "test"; // should be $a
$arr[3] = "test2"; // should be $b
$arr[1] = "this be d?"; // should be $d
$arr[2] = "or this be d?"; // should be $d
var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>
The output will be (PHP 4.3.3):
array(5) {
 [0]=>
 &string(4) "test"
 [1]=>
 &string(10) "this be d?"
 [2]=>
 string(13) "or this be d?"
 [3]=>
 &string(5) "test2"
 [4]=>
 &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"
So array_splice is reference safe, but you have to be careful about the generation of the replacement array.
have fun, cheers!


rolandfoxx

Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument.  Consider the following:
<?php
//Very truncated
class Tree {
 var $childNodes
 function addChild($offset, $node) {
   array_splice($this->childNodes, $offset, 0, $node);
   //...rest of function
 }
}
class Node {
 var $stuff
 ...
}
$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); //Expect 3?  wrong!
?>
In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof  I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it.  I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.
Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
 $firstPart = array_slice($array, 0, $offset);
 $secondPart = array_slice($array, $offset);
 $insertPart = array($insert);
 $array = array_merge($firstPart, $insertPart, $secondPart);
}
Note that this function makes no allowances for when $offset equals the first or last index in the array.  That's because array_unshift and array_push work just fine in those cases.  It's only array_splice that can trip you up.  Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.


leingang

array_splice resets the internal pointer of $input.  In fact, many array functions do this.  Caveat programmor!

gideon

array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.
Code:
<?php
$modarray = array_reverse($mili);
$trig=1;
foreach($modarray as $rubber => $glue) {
if($rubber!="
") {
$i++;
$b++;
if ($i==4) {
$trig++;
if($trig<=2) {
array_splice($modarray,$b,0,"
");
}elseif($trig>=3){
array_splice($modarray,$b+($trig-2),0,"
");
}
$i=0;
};
};
};
$fixarray = array_reverse($modarray);
?>


cyril carrez

array_splice does work when replacing with objects. As stated in the manual, you have to embed the object in an array:
<?php
array_splice ($myarray, $offset, 0, Array($myobjet));
?>


csaba

Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time.  The last two methods took significantly more time than the first two.  The most surprising lesson is that using the & incurs a time hit.
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
Csaba Gabor from Vienna


reverse esacdaehasinhoj

Also, a quick function to discard empty entries in an array which otherwise keeps keys intact:
<?php
 function remove_empty($inarray) {
     if (is_array($inarray)) {
         foreach($inarray as $k=>$v) {
             if (!(empty($v))) {
                 $out[$k]=$v;
             }
         }
         return $out;
     } else {
         return $inarray;
     }
 }
 // easy enough?
 print_r(remove_empty(array('', 'foo', '', 'bar', '', '', 'baz', '')));
?>
Should return:
Array
(
   [1] => foo
   [3] => bar
   [6] => baz
)


paule

Aiya, I feel silly. The fix for my code above assumes that your values in the associative array are strings. Ignore the fix code in my last post and use this instead:
<?php
               if(is_array($replacement))
                   foreach($replacement as $r_key=>$r_value)
                       $new_array[$r_key]=$r_value;
               elseif($replacement!==NULL)
                   $new_array[$key]=$replacement;
?>
Sorry again. I feel sheepish.  n.n


jrhardytwothousandtwo

A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well.  I hope this example will help others find what took me days to research.
--code begin--
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";
$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);
$original_array will now show:
1,2,3,blue,4,5
--code end---
Remember that you are telling the array to insert the element into the KEY position.  Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5.  And walla, you've inserted.  I can't say if this is of any value for named keys, or multidimensional arrays.  However it does work for single dimensional arrays.
$returned should be an empty array as nothing was returned.  This would have substance if you were doing a replace instead.


ahigerd

A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298


bitmor.co.kr

//orginal
IndexKey Bad Police
richard at richard-sumilang dot com
23-Nov-2002 04:27
<?php
function array_slice2($array, $val, $slice="name"){
switch($slice){
case "name":
while(list($i,$k)=each($array)){
if( $i != $val) { $return[$i]=$array[$i];  print "i = $i,val = $val
";}
else print " exit BugShow i = $i,val = $val
";
}
break;
case "variable":
while(list($i)=each($array)){
if($array[$i]!=$val) $return[$i]=$array[$i];
}
break;
}
return $return;
}
$list = array( "0" => "zero", "1" => "one", "2" => "two", "3" => "three", "4" => "four", "5" => "five", "6" => "six");
print_r( array_slice2 ( $list,'tne') );echo "
";
//YouWantShow     ? Array ( [0] => zero [1] => one [2] => two [3] => three [4] => four [5] => five [6] => six )
//But BugShow     ? Array ( [1] => one [2] => two [3] => three [4] => four [5] => five [6] => six )
//PrintShow
//exit BugShow i = 0,val = tne
//i = 1,val = tne
//i = 2,val = tne
//i = 3,val = tne
//i = 4,val = tne
//i = 5,val = tne
//i = 6,val = tne
?>

<?php
print_r( array_slice2 ( $list,"one","variable") );echo "
";
//Array ( [0] => zero [2] => two [3] => three [4] => four [5] => five [6] => six )
?>
//


kerxen

<?php
/** **************************
* Document::tableColumn()
*
* { This function sends back a column of the table or the table itself if it has only one column.
*   Input : $table, a table at 1 ou 2 dimensions or more
*           $numeroCol, the number of the column.
*   Output : $output : the column $numero of the table or the table.
*  }
*
**********  **********/
function tableColumn ( $table,  $numeroCol)
{
$output = array();
reset ($table) ;
if (!is_integer($numeroCol)) $numeroCol=0;
if (count($table)==0) return "UNDEFINED";
else { foreach ($table as $ligne)    // $ligne est un tableau (si $table est en 2D) ou un string ($table en 1D)
      { if (gettype($ligne)!="array")
           {
           if (strlen($ligne)!=0) array_push ($output, $ligne) ;    // on met le string dans $output
           else array_push ($output, " ") ;                         // on met une chaine " " dans $output
           }
        else
           {
           if (strlen($ligne[$numeroCol])!=0) array_push ($output, $ligne[$numeroCol]) ;     // on insere la colonne $numero de la ligne dans $output
           else  array_push ($output, " ") ;                                           // on met une chaine " " dans $output
           }
      }
      return $output;
    }
}
?>
/***************************/
SYNOPTIC : how to use it :
/***************************/
try the exemple below :
<?php
$stack = array ("orange", "banane");
array_push ($stack, "pomme", "bleuet");
$stock =  array ($stack,$stack);
print_r ($stock); echo '
';
print_r ($stack); echo '
';
print_r (tableColumn ($stock,0)) ;   echo '
';
print_r (tableColumn ($stock,1)) ;   echo '
';
print_r (tableColumn ($stock,2)) ;   echo '
';
print_r (tableColumn ($stock,3)) ;   echo '
';
print_r (tableColumn ($stack,0)) ;   echo '
';
print_r (tableColumn ($stack,1)) ;   echo '
';
?>
YOU WILL GET THIS :
Array ( [0] => Array ( [0] => orange [1] => banane [2] => pomme [3] => bleuet ) [1] => Array ( [0] => orange [1] => banane [2] => pomme [3] => bleuet ) )
Array ( [0] => orange [1] => banane [2] => pomme [3] => bleuet )
Array ( [0] => orange [1] => orange )
Array ( [0] => banane [1] => banane )
Array ( [0] => pomme [1] => pomme )
Array ( [0] => bleuet [1] => bleuet )
Array ( [0] => orange [1] => banane [2] => pomme [3] => bleuet )
Array ( [0] => orange [1] => banane [2] => pomme [3] => bleuet )
/**************************/
Good Luck
Eddy Cingala


fontajos

<?php
 // This function deletes a element in an array, by giving it the name of a key.
 function delArrayElementByKey($array_with_elements, $key_name) {
     $key_index = array_keys(array_keys($array_with_elements), $key_name);
     if (count($key_index) != '') {
         // Es gibt dieses Element (mindestens einmal) in diesem Array, wir loeschen es:
         array_splice($array_with_elements, $key_index[0], 1);
     }
     return $array_with_elements;
 }// End function delArrayElementByKey
?>


08-mar-2007 11:58

<?
class _test
{
public $first='test::1';
public $second='test::2';
}
$array=array(1,2,3,4,5);
echo '<pre>',var_Dump($array),'</pre>';
/* output:
array(5) {
 [0]=>
 int(1)
 [1]=>
 int(2)
 [2]=>
 int(3)
 [3]=>
 int(4)
 [4]=>
 int(5)
}
*/
array_Splice($array,3,0,new _test);
echo '<pre>',var_Dump($array),'</pre>';
/* output:
array(7) {
 [0]=>
 int(1)
 [1]=>
 int(2)
 [2]=>
 int(3)
 [3]=>
 string(7) "test::1"
 [4]=>
 string(7) "test::2"
 [5]=>
 int(4)
 [6]=>
 int(5)
}
*/
?>
lesson: array_Splice (and maybe more others functions) takes objects like arrays
advice: close object in array
<?array_Splice($array,$x,0,array($object))?>


Change Language


Follow Navioo On Twitter
array_change_key_case
array_chunk
array_combine
array_count_values
array_diff_assoc
array_diff_key
array_diff_uassoc
array_diff_ukey
array_diff
array_fill_keys
array_fill
array_filter
array_flip
array_intersect_assoc
array_intersect_key
array_intersect_uassoc
array_intersect_ukey
array_intersect
array_key_exists
array_keys
array_map
array_merge_recursive
array_merge
array_multisort
array_pad
array_pop
array_product
array_push
array_rand
array_reduce
array_reverse
array_search
array_shift
array_slice
array_splice
array_sum
array_udiff_assoc
array_udiff_uassoc
array_udiff
array_uintersect_assoc
array_uintersect_uassoc
array_uintersect
array_unique
array_unshift
array_values
array_walk_recursive
array_walk
array
arsort
asort
compact
count
current
each
end
extract
in_array
key
krsort
ksort
list
natcasesort
natsort
next
pos
prev
range
reset
rsort
shuffle
sizeof
sort
uasort
uksort
usort
eXTReMe Tracker