Googlebot
Googlebot

Reputation: 15683

Getting all sequential elements of an array

I want to implode all sequential elements of an array.

$array = array('First', 'Second', 'Third', 'Fourth');

The output should be

First
Second
Third
Fourth
First Second
Second Third
Third Fourth
First Second Third
Second Third Fourth
First Second Third Fourth

I started with an idea of using array_slice,

$l = count($array);
for($i=0;$i<$l;$i++){
    echo implode(' ',array_slice($array,$i,$l-$i)).PHP_EOL;
}

but I realised it is a bad idea, as I will need another loop.

What is the fast and neat way to do so?

Upvotes: 0

Views: 48

Answers (1)

Yoshi
Yoshi

Reputation: 54649

You can do this with nested loops, like:

$in  = ['First', 'Second', 'Third', 'Fourth'];
$out = [];

// this loop handles the max length/number of elements
for ($len = 1, $lim = count($in); $len <= $lim; $len++) {
    // this loop handles the starting index
    for ($i = 0; $i <= $lim - $len; $i++) {
        // collect
        $out[] = array_slice($in, $i, $len);
    }
}

foreach ($out as $set) {
    echo implode(', ', $set), "\n";
}

Demo: https://3v4l.org/AjOsb

Upvotes: 3

Related Questions