Mewtei Mewtei - 12 days ago 9
PHP Question

implode array strings two by two - php

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,6

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)

Answer

You can do it like below:-

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

$arr = Array
(
    0 => 1,
    1 => 4,
    2 => 2,
    3 => 5,
    4 => 3,
    5 => 6,
    6 => 4,
    7 => 7
);

$new_array = array_chunk($arr,2); // break the array into sub-arrays of two-two values each

$my_string = ''; // an empty string
foreach ($new_array as $new_arra){ // iterate though the new chunked array

    $my_string .= implode('ts',$new_arra).','; // implode the sub-array and add to the variable
}

echo trim($my_string,','); // echo variable

Output:- 1ts4,2ts5,3ts6,4ts7

https://eval.in/686524