Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while
instead of foreach
.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator
with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With