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\');
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
.
<?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;
}
?>
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;
}