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!

share|improve this question

44% accept rate
feedback

2 Answers

up vote 10 down vote accepted
$mash = "";
$res = array();

foreach ($arr as $el) {
    $mash .= $el;
    array_push($res, $mash);
}
share|improve this answer
Nice, clean and simple – Mark Baker Jul 7 '10 at 7:41
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 7 '10 at 7: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 7 '10 at 7:52
Surprisingly, I've found $res[] = $mash faster than using the array_push() function – Mark Baker Jul 7 '10 at 7:56
@Mark baker What's surprising about that? If you are adding just a single element, [] will be faster , of course. – Richard Knop Jul 7 '10 at 11:50
show 2 more comments
feedback
$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++;
}
share|improve this answer
You could do $newArray = array_fill(0,$finish,''); at the beginning and save the if – Lombo Jul 7 '10 at 7: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 7 '10 at 7:55
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.