tollmanz
tollmanz

Reputation: 3223

Combine/Merge 2 arrays while re-indexing in PHP

I think there is a function for what I want, but I cannot find it in the PHP docs. Let's imagine I have the following arrays:

$first = array(
    0 => 'howdy',
    1 => 'hello',
    2 => 'wassup'
);

$second = array(
    0 => 'aloha',
    1 => 'yo',
    2 => 'hi'
);

In the end, I want to combine them to be something like:

array(
    0 => 'howdy',
    1 => 'hello',
    2 => 'wassup',
    3 => 'aloha',
    4 => 'yo',
    5 => 'hi'   
)

The two important criteria are:

1) No values with equivalent keys or values are overwritten

2) The array is re-indexed, maintaining the order of the keys within the individual arrays and the first array's values have lower key values that the second array.

I know how I could do this writing a function, but I swear that there is a PHP function that does that and I want to use it if someone can identify it for me.

Upvotes: 0

Views: 625

Answers (1)

user142162
user142162

Reputation:

I think you are looking for array_merge():

array_merge($first, $second);

Result:

Array
(
    [0] => howdy
    [1] => hello
    [2] => wassup
    [3] => aloha
    [4] => yo
    [5] => hi
)

Upvotes: 2

Related Questions