Increasing array elements while in foreach loop in php? [duplicate]
Asked Answered
A

6

6

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.

Anoa answered 26/3, 2014 at 6:56 Comment(4)
"It is not displaying 'a'", what do you mean?Amain
Cannot ReproduceThose
@Rikesh: please find it hereAnoa
@Those see stdout sectionAnoa
L
3

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';
}
Ludendorff answered 26/3, 2014 at 7:6 Comment(0)
N
0

I think you need to store array element continue sly

Try

<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
   print "key=>$key\n";
   if(!isset($arr['a']))
      $arr['a'][] = 'apple';
}
print_r($arr);
?>
Notability answered 26/3, 2014 at 7:2 Comment(0)
P
0

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

https://www.php.net/manual/en/control-structures.foreach.php

Prodigal answered 26/3, 2014 at 7:6 Comment(0)
B
-1

Try this:

You will get values.

<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
   print "key=>$key\n";
   if(!isset($arr['a']))
      $arr['a'] = 'apple';
}

echo '<pre>';
print_r($arr);

?>

Output:

key=>b
<pre>Array
(
    [b] => book
    [a] => apple
)
Bochum answered 26/3, 2014 at 7:2 Comment(3)
Pl accept so others will get help from this ....Bochum
Did you read the question? It is: why adding new key had no effect during loop (not how to output array)Lungan
please read the question once againAnoa
L
-1

If you want to check key exist or not in array use array_key_exists function

Eg:

<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr);          // prints Array ( [b] => book ) 
if(!array_key_exists("a",$arr))
      $arr['a'] = 'apple';
print_r($arr);         // prints Array ( [b] => book [a] => apple )
?>

If you want to use isset condition try like this:

$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
   print "key=>$key\n";
   if(!isset($arr["a"]))
   {
        $flag = 1;
   }
}
if(flag)
{
     $arr['a'] = 'apple';
}

print_r($arr);
Ligan answered 26/3, 2014 at 7:2 Comment(1)
you need not to check even, try removing isset check and then runAnoa
S
-1

How about using for and realtime array_keys()?

<?php
$arr = array();
$arr['b'] = 'book';

for ($x=0;$x<count($arr); $x++) {
   $keys = array_keys($arr);
   $key = $keys[$x];
   print "key=>$key\n";
   if(!isset($arr['a']))
      $arr['a'] = 'apple';
}
Selfhypnosis answered 26/3, 2014 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.