0

I have two arrays that are inside foreach loop, I want to merge them to one key and value.

let the first array "array1" inside foreach:

$array1 = ['x', 'y', 'z'];

let the second array "array2" inside foreach:

$array2 = ['a', 'b', 'c'];

Expected output should be as follows:

$mergeArray = [0=>['x', 'y', 'z','a', 'b', 'c']];

What I have done is the following:

$mergeArray = [];

foreach ($customer as $key => $value) {

    $mergeArray[] = $value['items1'];
    $mergeArray[] = $value['items2'];

   echo '<pre>';     
   print_r($mergeArray);
   exit;

}

Thanks and welcome all suggestions

6
  • Doesn't array_merge($array1, $array2) do what you want? Commented Mar 1, 2018 at 18:22
  • @Barmar, i want merge as single key and value as shown $mergeArray Commented Mar 1, 2018 at 18:24
  • The array you show is equivalent to [0 => 'x', 1 => 'y', 2 => 'z', ...] Commented Mar 1, 2018 at 18:24
  • It's not a single key, you just didn't show all the other array keys. Commented Mar 1, 2018 at 18:25
  • Did you mean [0 => ['x', 'y', 'z', 'a', 'b', 'c']]? Commented Mar 1, 2018 at 18:25

3 Answers 3

0

Use array_merge:

$mergeArray[] = array_merge($value['item1'], $value['item2']);

Also, the exit should not be in the loop, that will prevent the loop from repeating.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do it with this code

   $mergeArray = [];

  foreach ($customer as $key => $value) {

$mergeArray[0] =array_merge ( $value['items1'],  $value['items2']); 

  echo '<pre>';     
  print_r($mergeArray);
  exit; 
 }

Comments

0

Why use a foreach loop at all? Am I missing something?

$array1 = array('x', 'y', 'z');

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

$mergeArray[0] = array_merge($array1, $array2);

Output:

Array
(
    [0] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => a
            [4] => b
            [5] => c
        )

)

2 Comments

You redid the question after I gave my answer. I will edit mine to do what you are now requesting.
Why the negative rating? I answer the question clearly and have updated it according to new information provided by the OP.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.