0

Hi, I am trying to get two arrays elements with the same key to me merged together.

array1 = array(0=>"1", 1=>"2", 2=>"3");
array2 = array(0=>"a", 1=>"b", 2=>"c");
foreach ($array1 as $origKey => &$subArray) 
  foreach ($array2[$origKey] as $key => $val) 
     $subArray[$key] = $val;

The ouptut required:

array(0=>"1a", 1=>"2b", 2=>"3c")

Can somebody help me, please?

5 Answers5

1

Use the following function to combine values

function combineValues($a1, $a2){
    foreach ($a1 as $k => $v) 
         $r[$k] = $v . $a2[$k];
    return $r;
}
zrinath
  • 106
  • 4
0

Here you go:

<?php

$array1 = array(0=>"1", 1=>"2", 2=>"3");
$array2 = array(0=>"a", 1=>"b", 2=>"c");

$sub = [];
foreach ($array1 as $key => $value) {
    array_push($sub, $value.$array2[$key]);
}

var_dump($sub);

->

array(3) {
  [0]=>
  string(2) "1a"
  [1]=>
  string(2) "2b"
  [2]=>
  string(2) "3c"
}
Gab
  • 3,404
  • 1
  • 11
  • 22
0
<?
$array1 = array(0=>"1", 1=>"2", 2=>"3");
$array2 = array(0=>"a", 1=>"b", 2=>"c");

foreach ($array1 as $origKey => &$subArray) 
  $new[] = $subArray.$array2[$origKey];


print_r($new);
//Output: Array ( [0] => 1a [1] => 2b [2] => 3c )
Fernando Torres
  • 460
  • 7
  • 24
0
your this statement foreach ($array2[$origKey] as $key => $val) is wrong 
that part $array[$origkey] coz in foreach $key as $value this basically evaluates whole array so use this way ....

 <?php
 $array1 = array(0=>"1", 1=>"2", 2=>"3");
 $array2 = array(0=>"a", 1=>"b", 2=>"c");
 $array3 = array();
 for($i=0 ;$i<3 ;$i++)
{
  $array3[] = $array1[$i].$array2[$i];
}
foreach($array3 as $merge)
 {
     echo $merge."<br>";
 }
 ?>
Mohit_
  • 49
  • 1
  • 7
0

let's get to the point, this will only work for a 1 dimension arrays of any lenghts :

$concatted_array = array(); // the new array

// if the 2 arrays don't have te same lenght, get the largest array
$max_array_length = (count($array1) > count($array2)) ? count($array1) : count($array1);

// loop for the longest array
for ($i=0; $i <$max_array_length ; $i++) {

  if($i < count($array1) && $i < count($array2)) // if the element exist for both arrays
  {
    $concatted_array[$i] = $array1[$i].$array2[$i];

  } elseif($i < count($array1)) // if element only exists in $array1
  {
      $concatted_array[$i] = $array1[$i];

  } else // if element only exists in $array2
  { 

      $concatted_array[$i] = $array2[$i];
  }
}

var_dump($concatted_array);

Here is the output :

array (size=3)
  0 => string '1a' (length=2)
  1 => string '2b' (length=2)
  2 => string '3c' (length=2)

Now here are some tips just in case you had errors with the code you wrote :

  • Don't forget the $ before variables.
  • foreach should be used only on arrays or object, so don't do foreach ($array2[$origKey] as $key => $val) unless $array2[$origKey] is an array or object itself. visit foreach documentation for more info.
Ahmed Rafik Ibrahim
  • 538
  • 1
  • 4
  • 16