views:

69

answers:

2

Hey.

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!

+10  A: 
$mash = "";
$res = array();

foreach ($arr as $el) {
    $mash .= $el;
    array_push($res, $mash);
}
Borealid
Nice, clean and simple
Mark Baker
Maybe it'd be even better if I'd used $res[] = $mash. But that's a real PHPism :-p. Thanks for the compliment, anyhow.
Borealid
You could actually do `$res[] = ($mash .= $el);` and save a whole line. :P I'd prefer the `[]` syntax over `array_push` either way though.
deceze
Surprisingly, I've found $res[] = $mash faster than using the array_push() function
Mark Baker
@Mark baker What's surprising about that? If you are adding just a single element, [] will be faster , of course.
Richard Knop
http://stackoverflow.com/questions/2431629/php-array-push-vs-myarray
Richard Knop
True enough. I'd thought about the function call overhead, but hadn't considered the option of passing multiple entries to push onto the array
Mark Baker
A: 
$newArr = array();
$finish = count($arr);
$start = 0;
foreach($arr as $key => $value) {
   for ($i = $start; $i < $finish; $i++) {
      if (isset($newArray[$i])) {
         $newArray[$i] .= $value;
      } else {
         $newArray[$i] = $value;
      }
   }
   $start++;
}
Mark Baker
You could do $newArray = array_fill(0,$finish,''); at the beginning and save the if
Lombo
@Lombo - True enough, and getting rid of the if within the loop would make it more efficient... but following Borealid's very efficient answer, I was just providing a basic alternative rather than a serious method
Mark Baker