0

I don't think this is a duplicate, but maybe I'm just not using good keywords. I need to take a 2D array and add in another 2D array such that

$arr  = array(array(1,2), array(3,4), array(7,8));
$arr2 = array(array(5,6));
array_splice($arr, ?, ?, $arr2);

Would give me back

[0] => 1,2
[1] => 3,4
[2] => 5,6
[3] => 7,8

I'm at a loss at how to do this, as the documentation isn't clear how to not remove any of the array but still add to it.

Thanks.

2
  • array_merge ? Commented Jan 3, 2014 at 13:47
  • No, they have to be in order. Commented Jan 3, 2014 at 14:36

3 Answers 3

1

If you really want to use array_splice(), then you want to insert at position 2 and use an offset of 0 (neither positive nor negative) so you don't remove any existing values but move them up in position:

$arr  = array(array(1,2), array(3,4), array(7,8));
$arr2 = array(array(5,6));
array_splice($arr, 2, 0, $arr2);
Sign up to request clarification or add additional context in comments.

Comments

0

Use array_merge

<?php

$arr  = array(array(1,2), array(3,4), array(7,8));
$arr2 = array(array(5,6));
$result = array_merge($arr, $arr2);

print_r($result);

http://codepad.org/B0ckNCpM

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
        )

    [3] => Array
        (
            [0] => 5
            [1] => 6
        )
)

2 Comments

:) I would if Make Baker hadn't given me an easier solution.
0

Array Merge Will do this for you.

LIVE TEST: https://eval.in/85459

$arr  = array(array(1,2), array(3,4), array(7,8));
$arr2 = array(array(5,6));
$arr = array_merge($arr,  $arr2);
print_r($arr);

OUTPUT:

   Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 7
            [1] => 8
        )

    [3] => Array
        (
            [0] => 5
            [1] => 6
        )

)

array_splice() is use for remove elements from an array and replace it with new elements.

1 Comment

You need to assign array_merge to a variable. Look at your output - it didn't include $arr2.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.