0

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?

4
  • interesting question, can you explain the use case? Commented Aug 20, 2021 at 11:02
  • @Erik it's text analysis, for getting sequential words in a phrase. Something like n-gram. Commented Aug 20, 2021 at 11:04
  • and you want to do this for an infinite amount of elements and up to any given depth? Commented Aug 20, 2021 at 11:16
  • @Erik yes, we have no predefined length, though it is not infinite in practice. Commented Aug 20, 2021 at 11:18

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.