php - How can I convert multiple arrays into one single variable string? -
i have 3 arrays this:
$a = ["a1", "a2", "a3", "a4", "a5"]; $b = ["b1", "b2", "b3", "b4", "b5"]; $c = ["c1", "c2", "c3", "c4", "c5"];
i looking way convert 3 arrays single string , save in variable this:
$abc = "a1 , b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5";
i have tried imploding, maybe method not good. using php 5.4.
note
please note following code can used, not willing use it. works me, feel reinventing 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, ","); }
this should work you:
just loop through 3 arrays @ once array_map()
. first transpose array format:
array ( [0] => a1, b1, c1 [1] => a2, b2, c2 [2] => a3, b3, c3 [3] => a4, b4, c4 [4] => a5, b5, c5 )
then implode()
array 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
Comments
Post a Comment