This can be achieved with a one-liner that unconditionally pushes that joined strings of the last two elements after consuming them with array_splice()
. In other words, the last two elements are removed, joined, then re-pushed into the array as a single element.
The $temp
variable in @solash58's answer is not necessary -- the consumption of the last two elements will occur before the auto-incremented index is generated.
Code: (Demo)
$array = [
0 => "a,b",
1 => "c,d",
2 => "e,f",
3 => "g,h",
];
$array[] = implode(",", array_splice($array, -2));
var_export($array);
Output:
array (
0 => 'a,b',
1 => 'c,d',
2 => 'e,f,g,h',
)