Teifion
Teifion

Reputation: 110979

Combining php arrays

I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).

$array1 = array(1 => 'a', 2 => 'b');
$array2 = array(3 => 'c', 4 => 'd');

Essentially I want to combine the two arrays as if it were something like this

$array3 = array(1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd');

Thanks

Upvotes: 4

Views: 1192

Answers (3)

Gil
Gil

Reputation:

You can check array_combine function.

Upvotes: 0

tonio
tonio

Reputation: 2376

array_merge only keeps STRING keys. You have to wrote your function for doing this

Upvotes: -2

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

Use

$array3 = $array1 + $array2;

See Array Operators

By the way: array_merge() does something different with the arrays given in the example:

$a1=array(1 => 'a', 2 => 'b');
$a2=array(3 => 'c', 4 => 'd');
print_r($a1+$a2);
Array
(
    [1] => a
    [2] => b
    [3] => c
    [4] => d
)
print_r(array_merge($a1, $a2));
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Note the different indexing.

Upvotes: 27

Related Questions