Search code examples
phparraysmergesliceimplode

Restructure array to join elements from 3rd position to end of array and store as 3rd element


I have arrays like this:

Array(
    [0] => 85
    [1] => 85167920
    [2] => ELECTRICAL/ELECTRONIC
    [3] => DEVICES
    [4] => FOR
    [5] => REPELLING
    [6] => INSECTS
    [7] => (E.G.MOSQUITOES
    [8] => ETC)
)

and

Array(
   [0] => 85
   [1] => 851680
   [2] => ELECTRIC
   [3] => HEATING
   [4] => RESISTORS
)

I want arrays like this:

Array(
    [0] => 85
    [1] => 851680
    [2] => ELECTRIC HEATING RESISTORS
)

and

Array(
    [0] => 85
    [1] => 85167920
    [2] => ELECTRICAL/ELECTRONIC DEVICES FOR REPELLING INSECTS (E.G.MOSQUITOES ETC)
)

I am not sure about what method to use: merge / combine / push.
What should I use?


Solution

  • Use array_slice() and implode()

    Method: (Demo)

    $array=[85,851680,'ELECTRIC','HEATING','RESISTORS'];
    $array=[$array[0],$array[1],implode(' ',array_slice($array,2))];
    var_export($array);
    

    Output:

    array (
      0 => 85,
      1 => 851680,
      2 => 'ELECTRIC HEATING RESISTORS',
    )