0
$arr1 = array(1,2,3); 
$arr2 = array("a","b","c"); 
$arr3 =array("1a","2b","3c");

How can I do the following ?

print

$one = 1,a,1a
$two = 2,b,2b
$three = 3,c,3c

3 Answers 3

3

Use array_map() function to map through all arrays at the same time. Like this :

$array_merged = array_map(function($v1,$v2,$v3) {
    return $v1 . ','. $v2 . ',' . $v3;
}, $arr1, $arr2, $arr3);
/*
Array (
    [0] => "1,a,1a",
    [1] => "2,b,2b",
    [2] => "3,c,3c",
)
*/
Sign up to request clarification or add additional context in comments.

2 Comments

nice one with array_map
very clean solution +1
1

You can try this:

$arr1 = array(1,2,3); 
$arr2 = array("a","b","c"); 
$arr3 = array("1a","2b","3c");

$i = 0;
foreach ($arr1 as $key => $value) {
    $newArr[] = $value.",".$arr2[$i].",".$arr3[$i];
$i++;
}
echo implode("<br/>", $newArr);

Result:

1,a,1a
2,b,2b
3,c,3c

You can also perform this by using for loop.

4 Comments

it does not help him to get the expected result
@jiboulex: yes you are right, answer updated, please check
Thank you my friend, you saved my live <3 :)
you are welcome, now chose the best answer and mark as accepted because its very important for other who still facing this issue.
0

Try this:

$arr1 = [1,2,3]; 
$arr2 = ["a","b","c"]; 
$arr3 = ["1a","2b","3c"];

$matrix = [$arr1, $arr2, $arr3];

var_dump(transpose($matrix));

function transpose($matrix) {

    return array_reduce($matrix, function($carry, $item) {
        array_walk($item, function ($value, $key) use (&$carry) {
            $carry[$key][] = $value;
        });
        return $carry;
    });
}

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.