Merge or combine PHP Array

Asked

Viewed 64 times

1

I’d like to combine two arrays ($a and $b) in such a way $c = $a[0]$b[0],$a[1]$b[1]...$a[n]$b[n] how to proceed there is a function I tried to do with foreach but without success.

$array1 = array("laranja", "morango");
$array2 = array("s1", "s2");
$result = array_combine($array1, $array2);

In case I would like as a result:

['laranja', 's1', 'morango', 's2']
  • 1

    Do you want the result this way? "orange", "S1", "strawberry", "s2"?

  • even in this way

1 answer

2


You can do it this way:

$array1 = array("laranja", "morango");
$array2 = array("s1", "s2");

$new = array();
for ($i=0; $i<count($array1); $i++) {
   $new[] = $array1[$i];
   $new[] = $array2[$i];
}
var_export($new);

Or

$array1 = array("laranja", "morango");
$array2 = array("s1", "s2");

$result = array();
array_map(function ($a, $b) use (&$result) { array_push($result, $a, $b); }, $array1, $array2);
var_export($result);

Upshot:

array ( 0 => 'orange', 1 => 'S1', 2 => 'strawberry', 3 => 's2', )

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.