4

How can I add to the array that I'm using foreach on?

for instance:

$t =array('item');
$c = 1;
foreach ($t as $item) {
    echo '--> '.$item.$c;
    if ($c < 10) {
        array_push($t,'anotheritem');
    }
}

this seems to produce only one value ('item1'). It seems that $t is only being evaluated once (at first time of foreach use) but not after it enters the loop.

4
  • 3
    It might be suitable to use a for loop instead: for($i = 0; $i < count($t); $i++) { /* your code */ } Commented Aug 10, 2014 at 21:30
  • you should be creating NEW array, not manipulating the one your currently looping through Commented Aug 10, 2014 at 21:36
  • @scrowler - that's a good suggestion. I'll have to switch to that. Commented Aug 10, 2014 at 21:45
  • @Dagon - that won't work for me. I'm trying to have it keep looping through the newly created elements as well. The operation I'm doing is obviously more complicated than my example. I'm actually splitting up time intervals based on values, and if a new one is created, I need to cycle through that one as well. Thanks for your input though Commented Aug 10, 2014 at 21:47

2 Answers 2

7

foreach() will handle the array you pass into it as a static structure, it can't be dynamic as far as the number of iterations go. You can change the values by passing the value of the iteration by reference (&$value) but you can't add new ones in the same control structure.

for()

for() will let you add new ones, the limit you pass will be evaluated each time, so count($your_array) can be dynamic. Example:

$original = array('one', 'two', 'three');
for($i = 0; $i < count($original); $i++) {
    echo $original[$i] . PHP_EOL;
    if($i === 2)
        $original[] = 'four (another one)';
};

Output:

one
two
three
four (another one)

while()

You can also define your own custom while() loop structure using a while(true){ do } methodology.

Disclaimer: Make sure if you're doing this that you define an upper limit on where your logic should stop. You're essentially taking over the responsibility of making sure that the loop stops somewhere here instead of giving PHP a limit like foreach() does (size of array) or for() where you pass a limit.

$original = array('one', 'two', 'three');
// Define some parameters for this example
$finished = false;
$i = 0;
$start = 1;
$limit = 5;

while(!$finished) {
    if(isset($original[$i])) {
        // Custom scenario where you'll add new values
        if($i > $start && $i <= $start + $limit) {
            // ($i-1) is purely for demonstration
            $original[] = 'New value' . ($i-1);
        }

        // Regular loop behavior... output and increment
        echo $original[$i++] . PHP_EOL;
    } else {
        // Stop the loop!
        $finished = true;
    }
}

See the differences here.

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

1 Comment

Wow, a lot more complex than I expected. Thanks for following up.
2

Thanks Scowler for the solution. It was posted in the comments and although he replied with an answer, it wasn't as simple as his first commented suggestion.

$t =array('item');
$c = 1;
for ($x=0; $x<count($t); $x++) {
    $item = $t[$x];
    echo '--> '.$item.$c;
    if ($c < 10) {
        array_push($t,'anotheritem');
    }
    $c++;
}

Works Great! count($t) is re-evaluated each time it goes through the loop.

1 Comment

+1 for answering your own question - I'm not sure how I missed it but I somehow thought my original example (for) didn't re-evaluate, you've proven me wrong.

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.