1

I have two arrays:

$array1 = array("A","One","C","Z");
$array2 = array("B","K","2","5");

Is there some built-in PHP way to get a final array with (I don't know how to say it, maybe 1-1 correspondence addition) alternate keys appended to each other like this

$final_array = array("A","B","One","K","C","2","Z","5");

If I use array_merge, I get:

$final_array = array("A","One","C","Z","B","K","2","5")

But that's exactly what an array_merge does. Is there any workaround other than looping?

Awais Umar
  • 2,027
  • 3
  • 27
  • 46
  • 3
    There isn't. You need to create your own function that will alternate between keys of two arrays. This becomes even more tricky if your arrays aren't the same length and the requirement is extremely weird - I've no clue why you'd need to alternate array keys, since you haven't specified why, but you need to write your own function. – N.B. Dec 10 '16 at 11:51
  • you need a function and a foreach – Rafael Shkembi Dec 10 '16 at 11:52
  • In this case there's no workaround. Loop through both arrays and add values sequentally. – u_mulder Dec 10 '16 at 11:52

1 Answers1

2

Try this:

$array1 = array(1,3,5,7);
$array2 = array(2,4,6,8);
$final_array = array_merge($array1,$array2);
sort($final_array);
print_r($final_array);

Hope this helps. Sorted the array using the sort function.

Kinshuk Lahiri
  • 1,468
  • 10
  • 23
  • Thank you for the answer and I am sorry I didn't created an appropriate question. There won't be any sort possible. Please check my updated question. – Awais Umar Dec 10 '16 at 11:48