Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Two Arrays with numerical keys without overwriting the old keys

Tags:

arrays

php

I don't want to use array_merge() as it results in i misunderstood that all values with the same keys would be overwritten. i have two arrays

$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');

and would like to combine them resulting like this

array(0=>'foo', 1=>'bar',2=>'bar', 3=>'foo');
like image 400
Moak Avatar asked Nov 14 '10 07:11

Moak


People also ask

How do I merge two arrays with the same key?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.


3 Answers

array_merge() appends the values of the second array to the first. It does not overwrite keys.

Your example, results in:

Array ( [0] => foo [1] => bar [2] => bar [3] => foo )

However, If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Unless this was just an example to another problem you were having?

like image 162
Russell Dias Avatar answered Sep 30 '22 07:09

Russell Dias


Does this answer your question? I'm not sure exactly what you're trying to accomplish, but from your description it sounds like this will work:

$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');

foreach ($array2 as $i) {
    $array1[] = $i;
}

echo var_dump($array1);
like image 30
cdhowie Avatar answered Sep 30 '22 09:09

cdhowie


There are probably much better ways but what about:

 $newarray= array();
    $array1 = array(0=>'foo', 1=>'bar');
    $array2 = array(0=>'bar', 1=>'foo');

    $dataarrays = array($array1, $array2);

    foreach($dataarrays as $dataarray) {
        foreach($dataarray as $data) {
            $newarray[] = $data;
        }
    }

 print_r($newarray);
like image 42
dpmguise Avatar answered Sep 30 '22 08:09

dpmguise