1

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!

user367217
  • 499
  • 2
  • 6
  • 20

2 Answers2

10
$mash = "";
$res = array();

foreach ($arr as $el) {
    $mash .= $el;
    array_push($res, $mash);
}
Borealid
  • 95,191
  • 9
  • 106
  • 122
  • 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 Jul 07 '10 at 07:50
  • 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 Jul 07 '10 at 07:52
  • Surprisingly, I've found $res[] = $mash faster than using the array_push() function – Mark Baker Jul 07 '10 at 07:56
  • @Mark baker What's surprising about that? If you are adding just a single element, [] will be faster , of course. – Richard Knop Jul 07 '10 at 11:50
  • 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 Jul 07 '10 at 11:58
0
$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
  • 209,507
  • 32
  • 346
  • 385
  • You could do $newArray = array_fill(0,$finish,''); at the beginning and save the if – Lombo Jul 07 '10 at 07:42
  • @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 Jul 07 '10 at 07:55