How can I convert multiple arrays to one variable string?

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'm looking for a way to convert three arrays to a single string and store it in a variable like this:

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

      

I tried to imitate, but maybe my method is not that good. I am using PHP 5.4.

Note

Please note that the following code can be used, but I don't want to use it. This 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, ",");
}

      

+3


source to share


1 answer


This should work for you:

Just concatenate all 3 arrays at once with array_map()

. So first you transfer your array to 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 take 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

      

+4


source







All Articles