0

I know how to split my input string on spaces, but I need to generate an array of values where each element contains the previous string PLUS the next available word.

$str = "a nice and sunny day today";
$split = explode(' ', $str);

How could I possibly be left with an array that looks like the following:

$new[0] = 'a';
$new[1] = 'a nice';
$new[2] = 'a nice and';
$new[3] = 'a nice and sunny';

Instead of manually doing this

$new[] = $split[0];
$new[] = $split[0] . $split[1];
$new[] = $split[0] . $split[1] . $split[2];
$new[] = $split[0] . $split[1] . $split[2] . $split[3];

You can probably see the pattern that's happening.

Because this can happen for up to around 15 words, I'm seeking a shorter and dynamic way of doing this using a foreach/some kind of function.

2

6 Answers 6

1
$tmp = array();
$new = array();
for($i = 0; $i < count($split); $i++)
  {
    $tmp[] = $split[$i];
    $new[] = implode(' ',$tmp);
  }

Shorter code, reverse order:

$new = array();
for($i = count($split); $i >= 0; $i--)
  {
    $new[] = implode(' ',$split);
    array_pop($split);
  }

Which of course is not a problem according to array_reverse()

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

Comments

1

You can do this:

$str = "a nice and sunny day today";
$split = explode(' ', $str);

$newList = array();
// Non-empty string?
if($str) {
    // Add the first element
    $newList[] = $split[0];
    for($i = 1; $i < count($split); $i++) {
        // New element gets appended with previous
        $newList[] = $newList[$i-1] . " " . $split[$i];
    }
}

This is more efficient than executing implode every time, since we're only concatenating the current and previous string.

There's one more bit of inefficiency though - we're calling count every time. Lets not do that.

$newList[] = $split[0]
for($i = 1, $len = count($split); $i < $len; $i++) {
    // New element gets appended with previous
    $newList[] = $newList[$i-1] . " " . $split[$i];
}

Comments

0
<?php
$str = "1 2 3";
$split = explode(' ', $str);
/* 
now $split is array('1','2','3')

Need to convert it to: array('1','1 2','1 2 3')
*/
$n = count($split);
$output = array();
for ($i = 0; $i < $n; ++$i)
{
    $output[$i] = "";
    for ($j = 0; $j <= $i; ++$j)
    {
        $output[$i] .= $split[$j];
        if ($j != $i)
        {
            $output[$i] .= " ";
        }
    }
}

var_dump($output);

output:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(3) "1 2"
  [2]=>
  string(5) "1 2 3"
}

Comments

0

Just build the string in a loop and add to your array.

$str = "a nice and sunny day today";
$split = explode(' ', $str);
$final_array = array();

$i = 0;
$string = '';
$spacer = '';
for ($i = 0; $i < count($split); $i++) {
    $string .= $spacer . $split[$i];
    $final_array[] = $string;
    $spacer = ' ';
}

Comments

0

You can use array_map() with a callback function to achieve this:

$result = array_filter(array_map(function($k) use($split) { 
    return implode(' ', array_slice($split, 0, $k)); 
}, array_keys($split)));

print_r(array_values($result));

Output:

Array
(
    [0] => a
    [1] => a nice
    [2] => a nice and
    [3] => a nice and sunny
    [4] => a nice and sunny day
)

Demo.

Comments

0

I lean, direct solution should not be using more than one loop or more than one function call (after exploding, of course).

I'll demonstrate a functional-style solution with array_map(). The static declaration allows a value to be retained for access during subsequent iterations.

Code: (Demo) (Uglier version)

var_export(
    array_map(
        function ($word) {
            static $last;                            // declare persistent variable in scope
            $word = ($last ? "$last " : '') . $word; // prepend previous word(s)
            return $last = $word;                    // update $last and return $word (which is identical to $last)
        },
        explode(' ', $str)
    )
);

Or as shown in my other answer: (Demo)

var_export(
    array_map(
        function ($word) {
            static $last;
            return ltrim($last .= " $word");
        },
        explode(' ', $str)
    )
);

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.