1

What is the most simple way to concatenate two arrays to become side by side?

Here is $Arr1

Array
(
    [0] => Windows
)

and here is $Arr2

Array
(
    [0] => 5.0
)

How would I combine them so that $Arr[0] = "Windows5.0"?

array_merge($Arr1, $Arr2) Adds $Arr2 to be below $Arr1 which is not what I want

Bijan
  • 7,737
  • 18
  • 89
  • 149

4 Answers4

3

array_combine may work for you as long as each array is equal length and the keys are valid. This will structure your data better and then you can use a foreach loop.

<?php
  $a = array('Windows', 'Mac', 'Linux');
  $b = array('5.0', '6.0', '3.14');
  $c = array_combine($a, $b);

  print_r($c);
?>

The above example will output:

Array
(
  [Windows]  => 5.0
  [Mac]    => 6.0
  [Linux] => 3.14
)

So if you need to get the value for Windows it would be:

<?php
  foreach($c as $key => value) {
    echo $key." ".$value."\n";
 }

?>

Which would display:

Windows 5.0
Mac 6.0
Linux 3.14
Grasshopper
  • 152
  • 1
  • 10
1

try this

$Arr1 = Array ( "Windows");
$Arr2 = Array ( " 5.0");

$arr = array( $Arr1[0] . $Arr2[0] );
var_dump($arr);

ouput

array (size=1)
  0 => string 'Windows 5.0' (length=11)
1

For your particular example, after you do array_merge, do implode on the resulting array, this will give you the desired output.

$Arr = [implode(array_merge($Arr1, $Arr2))]; // works for PHP 5.4+
$Arr = array(implode(array_merge($Arr1, $Arr2))) // for older versions

I have a suspicion that your requirements are a little more complex than that.

For more info on implode, see: http://php.net/manual/en/function.implode.php

If you would like to join the values from multiple entries, try using array_map:

$Arr1 = array('windows', 'floor', 'door');
$Arr2 = array('5.0', '6.0', '7.0');
$Arr = array_map(function($a, $b) { return $a . $b; }, $Arr1, $Arr2);

This will output:

    Array
    (
        [0] => windows5.0
        [1] => floor6.0
        [2] => door7.0
    )

For more info on array_map, see: http://php.net/manual/en/function.array-map.php

ymas
  • 474
  • 6
  • 10
0

This will work -- espacially interesting when doing with multiple values:

foreach ($arr1 as $key=>$value)
{
    $arr3[] = $value.$arr2[$key];

}

var_dump($arr3);

output:

array(1) { [0]=> string(10) "Windows5.0" }
baao
  • 71,625
  • 17
  • 143
  • 203