Linux Support, Hosting & Security Hertfordshire

Thursday, 11 March 2010

PHP: Insert an array into the middle of an array

Array into array

Ever needed to insert an array of items into the middle or at specific position in another php array?
Well this function may help; Download

CODE

<?php

$fruits = array("apple", "pear", "orange", "plum");
$insert = array("grape", "peach");

var_dump($fruits);
var_dump($insert);


array_insert($fruits, $insert, 2);

var_dump($fruits);



function array_insert(&$array, $insert, $position) {
settype($array, "array");
settype($insert, "array");
settype($position, "int");

//if pos is start, just merge them
if($position==0) {
    $array = array_merge($insert, $array);
} else {


    //if pos is end just merge them
    if($position >= (count($array)-1)) {
        $array = array_merge($array, $insert);
    } else {
        //split into head and tail, then merge head+inserted bit+tail
        $head = array_slice($array, 0, $position);
        $tail = array_slice($array, $position);
        $array = array_merge($head, $insert, $tail);
    }
}
}

?>

OUTPUT

array
0 => string 'apple' (length=5)
1 => string 'pear' (length=4)
2 => string 'orange' (length=6)
3 => string 'plum' (length=4)

array
0 => string 'grape' (length=5)
1 => string 'peach' (length=5)

array
0 => string 'apple' (length=5)
1 => string 'pear' (length=4)
2 => string 'grape' (length=5)
3 => string 'peach' (length=5)
4 => string 'orange' (length=6)
5 => string 'plum' (length=4)


One item into array

If you just need to insert one element, then as @Ryan pointed out, you can use array_splice.

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

Did this post help you? Thank us with bitcoin;

2 comments:

  1. Nice function. I have read elsewhere that array_splice should do the trick:

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

    ReplyDelete
  2. Thanks Ryan. That works great for single elements, so means this function is then only good for inserting arrays into arrays.

    I'll update the post.

    ReplyDelete