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)
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
You may use array_chunk function to split an array into parts first and then implode them as you wish.
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
Here is another way:
<?php
$a = Array(0 => 1,1 => 4,2 => 2,3 => 5,4 => 3,5 => 6,6 => 4,7 => 7);// your array
$i=1;
foreach ($a as $key => $value) {
if ($i % 2 != 0) {
$newArr[] = $value."ts".$a[$i];
}
$i++;
}
print_r($newArr);
?>
Output:
Array ( [0] => 1ts4 [1] => 2ts5 [2] => 3ts6 [3] => 4ts7 )
I know I might be late in answering but this may be helpful without using array_chunk
function and using single for
loop like as
$arr = Array
(
0 => 1,
1 => 4,
2 => 2,
3 => 5,
4 => 3,
5 => 6,
6 => 4,
7 => 7
);
$res = [];
$count = count($arr);
for($k = 0; $k < $count; $k+=2)
{
$res[] = isset($arr[$k+1]) ? "{$arr[$k]}ts{$arr[$k+1]}" : $arr[$k];
}
echo implode(",",$res);
Output:
1ts4,2ts5,3ts6,4ts7
Another way:
$array = [
0 => 1,
1 => 4,
2 => 2,
3 => 5,
4 => 3,
5 => 6,
6 => 4,
7 => 7,
];
$array = array_map( function( $item ) { return implode( 'ts', $item ); }, array_chunk( $array, 2 ) );
echo implode( ',', $array );