PHP Adding new key to the array used in foreach

NEW2WEB picture NEW2WEB · Aug 10, 2014 · Viewed 7.8k times · Source

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.

Answer

scrowler picture scrowler · Aug 11, 2014

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.