Is there any oneliner for a kind of explode and concat in PHP

Issue

I got string like 1_2_3_4_5 and I want an array like this:

array(
 [0] = 1
 [1] = 1_2
 [2] = 1_2_3
 [3] = 1_2_3_4
 [4] = 1_2_3_4_5
)

Any idea for a oneliner?

Solution

<?php

$input = '1_2_3_4_5';

// Get an array with 1, 2, 3, 4 and 5
$parts = explode('_', $input);

$output = [];

$i = 1;

foreach ($parts as $part) {
    // array_slice() will take 1 to n elements from the array of numbers
    $values = array_slice($parts, 0, $i++);
    // Join the values
    $output[] = implode('_', $values);
}

print_r($output);

It will show this:

Array
(
    [0] => 1
    [1] => 1_2
    [2] => 1_2_3
    [3] => 1_2_3_4
    [4] => 1_2_3_4_5
)

Try it at 3V4L.

Answered By – A.L

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published