Search code examples
phparraysimplode

Join every two array values with a word, then join those strings with a comma


My array is :

Array
(
    [0] => 1
    [1] => 4
    [2] => 2
    [3] => 5
    [4] => 3
    [5] => 6
    [6] => 4
    [7] => 7
)

I use this code: implode( ",", $output );

but it returns this: 1,4,2,5,3,6,4,7

I want to 0 comes with 1 and 2 comes with 3 and etc with "ts" between them. after both of them with "ts", it should come with a comma. like this :

1ts4,2ts5,3ts6,4ts7

summary: instead of odd commas (with the implode that I said), I want it to put "ts" (1ts4,2ts5,3ts6,4ts7)


Solution

  • Try below code:-

    $arr = [1,4,2,5,3,6,4,7];
    $strArr= [];
    for($i=0;$i<count($arr);$i=$i+2){
      $strArr[] = "{$arr[$i]}ts{$arr[$i+1]}";
    } 
    echo implode(',',$strArr);
    

    Edited