0

I want to combine three arrays into one I am expecting like output are using array_combine or array_merge

Likes
friends,
usa,
usa2,
..,
..,
so.on..,

$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');

$output = $array1+$array2+$array3;
echo "<pre>";
print_r($output);
echo "</pre>";

But here i am getting output as

likes,
friends,
USA
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Test
  • 69
  • 2
  • 7
  • Each of your arrays contain the same keys and, as the manual states: *The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.* - [see Array Operators](http://php.net/manual/en/language.operators.array.php) – billyonecan Jan 28 '18 at 17:00

4 Answers4

2

In PHP 5.6+ You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:

$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');

array_push($array1, ...$array2, ...$array3);
echo "<pre>";
print_r($array1);
echo "</pre>";

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
0

check this out custom function for array push

<?php

$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');


function push($array1,$array2){
    $return = array();
    foreach($array1 as $key => $value){
        $return[] = $value;
    }
    foreach($array2 as $key => $value){
        $return[] = $value;
    }
    return $return;
}

$array = push($array1,$array2);
$array = push($array,$array3);

print_r($array);
Ganesh Kandu
  • 601
  • 5
  • 15
0

If you want to have an array of arrays, each element at a given index having the values of the three arrays at the respecting index, then:

$length = count($array1);

$result = array();
for ($index = 0; $index < $length; $index++) {
    $result[]=array($array1[$index], $array2[$index], $array3[$index]);
}

If you simply want to put all items into a new array, then:

$result = array();
for ($index = 0; $index < count($array1); $index++) {
    $result[]=$array1[$index];
}
for ($index = 0; $index < count($array2); $index++) {
    $result[]=$array2[$index];
}
for ($index = 0; $index < count($array3); $index++) {
    $result[]=$array3[$index];
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
-1

Use Array Merge

$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');

$output = array_merge($array1,$array2,$array3);
echo "<pre>";
print_r($output);
echo "</pre>";
Minar Mnr
  • 1,376
  • 1
  • 16
  • 23