0

Am I overlooking a function in PHP that will merge arrays without preserving keys? I've tried both ways of these ways: $arrayA + $arrayB and array_merge($arrayA, $arrayB) but neither are working as I expected.

What I expect is that when I add array(11, 12, 13) and array(1, 2, 3) together that I would end up with array(11, 12, 13, 1, 2, 3).

I created a function of my own which handles it properly, though I was trying to figure out if it was the best way of doing things or if there's an easier or even a build in way that I'm just not seeing:

function array_join($arrayA, $arrayB) { foreach($arrayB as $B) $arrayA[] = $B; return $arrayA; } 

Edit: array_merge() was working as intended, however I had the function running in a loop and I was using the incorrect variable name inside the function, so it was only returning a partial list as is what I was experiencing. For example the loop I was using ended on array(13, 1, 2, 3).

1
  • What is the output you are getting? Commented Feb 8, 2014 at 6:32

3 Answers 3

2

Have you actually tested your code? because array_merge should be enough:

From the documentation of array_merge:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. (emphasis are mine)

<?php $a1 = array(11, 12, 13); $a2 = array(1, 2, 3); $x = array_merge($a1, $a2); print_r($x); 

It print this on my console:

Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 1 [4] => 2 [5] => 3 ) 
Sign up to request clarification or add additional context in comments.

1 Comment

I'm an idiot. I had a function running in a loop and I was using the wrong variable inside the array_merge function so I was only getting a partial list. I will mark your answer as accepted due to its robust explanation.
0
$arr1 = array(11, 12, 13); $arr2 = array(1, 2, 3); print_r(array_merge($arr1,$arr2)); 

Comments

0

Try this :

function array_join($arrayA, $arrayB) { foreach($arrayB as $B) $arrayA[count($arrayA)] = $B; return $arrayA; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.