Search code examples
phparraysloopsconcatenation

Prepend all preceding values to each element of an array


I have an array like this (one dimension only):

$arr = array('one', 'two', 'three', 'foo', 'bar', 'etc');

Now I need a for() loop that creates a new array from $arr, like that:

$newArr = array('one', 'onetwo', 'onetwothree', 'onetwothreefoo', 'onetwothreefoobar', 'onetwothreefoobaretc');

Seems to be simple but I can't figure it out.

Thanks in advance!


Solution

  • $mash = "";
    $res = array();
    
    foreach ($arr as $el) {
        $mash .= $el;
        array_push($res, $mash);
    }