0

i have a piece of code that joins two arrays together in PHP like this

    $array_1=[1,2,3,4]; //input 1
    $array_2= ["a","b","c","d"];//input 2
    $array_3= ["1 a", "2 b", "3 c", "4 d"]; //this is how my final array should look like

i tried using array merge but it did not do what i wanted it to do is there another function i can use to do this.

so basically i am trying to get the numbers from the array 1 and letters from the array 2 and join it together in array 3 in to a single array

2
  • 1
    Curly braces aren't arrays? Edit: I stand corrected, as per the documentation - Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above). Commented Apr 4, 2018 at 13:08
  • i have edited my code please check Commented Apr 4, 2018 at 13:09

4 Answers 4

9

You can just map the 2 arrays

$array_1 = array(1,2,3,4);
$array_2 = array('a','b','c','d');

$array_3 = array_map(function($a1, $a2) {
    return $a1 . " " . $a2;
}, $array_1, $array_2);

echo "<pre>";
print_r( $array_3 );
echo "</pre>";

This will result to:

Array
(
    [0] => 1 a
    [1] => 2 b
    [2] => 3 c
    [3] => 4 d
)
Sign up to request clarification or add additional context in comments.

Comments

4
<?php
$array_1=[1,2,3,4]; //input 1
$array_2= ['a','b','c','d'];//input 2

for($i=0;$i<count($array_1);$i++){
    $newArray[]=$array_1[$i].' '.$array_2[$i];
}

echo '<pre>';
print_r($newArray);

And the output is :

Array
(
    [0] => 1 a
    [1] => 2 b
    [2] => 3 c
    [3] => 4 d
)

Comments

0

Probably this is what you need. I assume that both of arrays contains equal quantity of elements.

function merge($array1, $array2) {
    $retArray = [];

    foreach ($array1 as $index => $value) {
        $retArray[] = $value . ' ' . $array2[$index];
    }

    return $retArray;
}

$array_1 = [1,2,3,4];
$array_2 = ["a", "b", "c", "d"];
$array_3 = merge($array_1, $array_2);

var_dump($array_3);

The result is:

array(4) {
  [0]=>
  string(3) "1 a"
  [1]=>
  string(3) "2 b"
  [2]=>
  string(3) "3 c"
  [3]=>
  string(3) "4 d"
}

Comments

0
$array_1=[1,2,3,4];
$array_2= ["a","b","c","d"];
$array_3 = [];
for ($i = 0; $i < min(count($array_1), count($array_2)); $i++) {
    array_push($array_3, sprintf("%d %s", $array_1[$i], $array_2[$i]));
}
var_dump($array_3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.