M.Svrcek
M.Svrcek

Reputation: 5635

dynamically changing array in foreach

is it possible somehow change array which is processed by foreach? I tried this script

$iterator = 10;
$cat = array(1 => 'a',2 => 'b',3 => 'c');

foreach ($cat as $k => $c)
{
    if ($iterator < 15)
    {
        $cat[$iterator] = $iterator;
        $iterator++;
    }
    echo $c;  
}

but it isn't changing the 'foreached' array. The output from foreach is

abc

but var_dump from array after foreach is

array(6) { [1]=> string(1) "a" [2]=> string(1) "b" [3]=> string(1) "c" [10]=> int(10) [11]=> int(11) [12]=> int(12) }

That means 10,11,12 were added in foreach cyclus, but foreach didn't iterate over them? Is it possible to do that? Or do I need to make 2foreach cyclus?

Upvotes: 1

Views: 301

Answers (3)

Alma Do
Alma Do

Reputation: 37365

Actually, you should not. Because foreach will work with copy of array. That means - it will firstly copy your array and then loop through it. And no matter if you'll change original array - since you're working with it's copy inside foreach, any modification will affect only original array and not looped copy.

But - yes, after foreach you will see your changes in original array. Besides, there is little sense in doing such thing. It's hard to read and may case unpredictable results.

One important thing that wasn't mentioned. The following wont work:

$iterator = 10;
$cat = array(1 => 'a');//only one element; same for empty array

foreach ($cat as $k => &$c)
{
    if ($iterator < 15)
    {
        $cat[$iterator] = $iterator;
        $iterator++;
    }
    echo $c;
}

-because of how PHP deals with array pointer in foreach.

Upvotes: 3

adamS
adamS

Reputation: 600

The internet needs more cats! pass the array by reference instead and you'll get the desired result. note the &$cat in the loop.

$iterator = 10;
$cat = array(1 => 'a',2 => 'b',3 => 'c');

foreach($cat as $k => &$c)
{
    if ($iterator < 15)
    {
        $cat[$iterator] = $iterator;
        $iterator++;
    }
    echo $c;  
}

Upvotes: 3

Dushyant Joshi
Dushyant Joshi

Reputation: 3702

<?php
$iterator = 10;
$cat = array(1 => 'a',2 => 'b',3 => 'c');

foreach ($cat as $k => &$c)//observe the '&'
{
    if ($iterator < 15)
    {
        $cat[$iterator] = $iterator;
        $iterator++;
    }
    echo $c;
} 
?>

Upvotes: 3

Related Questions