How to append one array to another without comparing their keys?

$a = array( 'a', 'b' );
$b = array( 'c', 'd' );

At the end it should be: Array( [0]=>a [1]=>b [2]=>c [3]=>d ) If I use something like [] or array_push, it will cause one of these results:

Array( [0]=>a [1]=>b [2]=>Array( [0]=>c [1]=>d ) )
//or
Array( [0]=>c [1]=>d )

It just should be something, doing this, but in a more elegant way:

foreach ( $b AS $var )
    $a[] = $var;
share|improve this question
3  
array_merge ($a, $b) should do exactly what you want, at least with PHP 5+. – tloach Nov 24 '10 at 16:15
(related) + Operator for Array in PHP – Gordon Nov 24 '10 at 16:17
3  
none of the outputs you posted come from array_merge(); the output of array_merge(); should be exaclty what you need: print_r(array_merge($a,$b)); // outputs => Array ( [0] => a [1] => b [2] => c [3] => d ) – acm Nov 24 '10 at 16:18

4 Answers

up vote 14 down vote accepted

array_merge is the elegant way:

$a = array('a', 'b');
$b = array('c', 'd');
$merge = array_merge($a, $b); 
// $merge is now equals to array('a','b','c','d');

Doing something like:

$merge = $a + $b;
// $merge now equals array('a','b')

Will not work, because the + operator does not actually merge them. If they $a has the same keys as $b, it won't do anything.

share|improve this answer

Why not use

$appended = array_merge($a,$b); 

Why don't you want to use this, the correct, built-in method.

share|improve this answer
Right, I'm so sorry for misunderstanding. It works exactly this way, thanks! – Danil K Nov 24 '10 at 16:20

How about this:

$appended = $a + $b;
share|improve this answer
1  
It will compare keys, as I said, and result with following: Array ( [0] => a [1] => b ) – Danil K Nov 24 '10 at 16:14
Are you sure it will compare keys? Says the documentation (emphasis mine): "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.". Are you sure your keys aren't actually '0' => 'a' ... instead of 0 => 'a' ? – Piskvor Nov 24 '10 at 16:17
1  
I've just tried it. – Danil K Nov 24 '10 at 16:19
@Piskvor there is no difference between '0' and 0 for keys. – Gordon Nov 24 '10 at 16:21
1  
@Gordon: Ah, you're right - that's what I get for thinking of two things at once. php.net/manual/en/language.operators.array.php is documentation for array + array – Piskvor Nov 24 '10 at 16:31
show 3 more comments
$a = array("a", "b"); $b = array("c", "d");

$a = implode(",", $a);
$b = implode(",", $b);

$c = $a . "," . $b;

$c = explode(",", $c);
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.