-3

I have an array like this:

$array = array(
    0 => "a,b",
    1 => "c,d",
    2 => "e,f",
    3 => "g,h", 
);

I would like to merge the last two array elements (2 and 3) into a one like this:

$array = array(
    0 => "a,b",
    1 => "c,d",
    2 => "e,f,g,h", 
);

How can I do it using PHP?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Optimus Prime
  • 308
  • 6
  • 22

3 Answers3

2

Remove tow last items by array_splice and add implode of them

$temp = array_splice($array,-2); 
$result = array_merge($array, (array) implode(',', $temp));

demo

As @Nick mentioned, you can do it by

$temp = array_splice($array,-2); 
$array[] = implode(',', $temp);
splash58
  • 26,043
  • 3
  • 22
  • 34
  • You already did change the source array with `array_splice`. That's why I made my suggestion... – Nick Aug 31 '19 at 00:19
1

Simple, use array_pop() to remove the last 2 elements, then concatenate them, then add them back to the original array.

$array = array(
    0 => "a,b",
    1 => "c,d",
    2 => "e,f",
    3 => "g,h", 
);

$element3 = array_pop($array); //grab value of the last element, and remove it from the array.
$element2 = array_pop($array); 

$array[] = "$element2,$element3";

this will always work if it's always supposed to be the last 2 elements.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
0

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',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136