2

I have three arrays like this:

$a = ["a1", "a2", "a3", "a4", "a5"];
$b = ["b1", "b2", "b3", "b4", "b5"];
$c = ["c1", "c2", "c3", "c4", "c5"];

I am looking for a way to convert the three arrays into a single string and save it in a variable like this:

$abc = "a1 , b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5";

I have tried imploding, but it maybe my method is not so good. I am using PHP 5.4.

Note

Please note that the following code can be used, but I am not willing to use it. It works for me, but I feel like reinventing the wheel:

array_push($abc, $a);
array_push($abc, ",");
array_push($abc, $b);
array_push($abc, ",");
array_push($abc, $c);

if ($key < (sizeof($a)-1)){
    array_push($abc, ",");
}
4
  • have you tried array_merge($array1, $array2);? php.net/manual/en/function.array-merge.php. On the right side there a few other posibilities Commented May 31, 2015 at 18:11
  • 1
    I find it a little funny that everyone rushed to submit that answer Commented May 31, 2015 at 18:22
  • So where are we with this question ? Commented May 31, 2015 at 19:23
  • The selected answer does exactly that I was looking for. The code that I had made involved using foreach(). I was pushing three arrays sequentially (i.e. [a1, b2, c1, a2, b2].....). Afterwards, I was going to either use implode or use another foreach() to add abc[] into a single string. Either way, it would have been chaotic compared to the selected answer. The selected answer on the other hand does this in just three lines of code. As David Thomas said in the comment of selected answer, "I forget, sometimes, that php can be quite beautiful." Commented Jun 1, 2015 at 6:47

1 Answer 1

4

This should work for you:

Just loop through all 3 arrays at once with array_map(). So first you transpose your array into this format:

Array
(
    [0] => a1, b1, c1
    [1] => a2, b2, c2
    [2] => a3, b3, c3
    [3] => a4, b4, c4
    [4] => a5, b5, c5
)

Then you implode() this array into your expected string.

Code:

<?php

    $a = ["a1", "a2", "a3", "a4", "a5"];
    $b = ["b1", "b2", "b3", "b4", "b5"];
    $c = ["c1", "c2", "c3", "c4", "c5"];

    $result = implode(", ", array_map(function($v1, $v2, $v3){
        return "$v1, $v2, $v3";
    }, $a, $b, $c));

    echo $result;

?>

output:

a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5
Sign up to request clarification or add additional context in comments.

3 Comments

Can you believe that I was about to post the same solution? :°D 25 second late
Nicely done, I forget, sometimes, that php can be quite beautiful.
Wow! This did precisely what I wanted. This technique replaced my 15 lines of code with just three! Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.