Jump to content

Recommended Posts

 <!DOCTYPE html>
<html>
<body>

<?php  
$colors = array("red", "green", "blue", "yellow"); 

foreach($colors as $x => $value):
  echo "$value <br>";
  if ($x == 1) $colors[] = "pink";
endforeach;
?>  

</body>
</html>

Getting error 

PHP Parse error: syntax error, unexpected '$colors' (T_VARIABLE) in /home/KhtmoB/prog.php on line 10

Edited by sen5241b
  • sen5241b changed the title to How to Add Element to end of currently Iterating array

When you use foreach() you iterate through a copy of the array elements but you are adding 'pink' to the original array.

To iterate through the original array you need to pass the values "by reference". For example

$colors = array("red", "green", "blue", "yellow"); 

foreach($colors as $x => &$value):                // note the "&"
  echo "$value <br>";
  if ($x == 1) $colors[] = "pink";
endforeach;

giving

red 
green 
blue 
yellow 
pink 

 

You can also use an ArrayIterator and the append method.

From a random project I was working on,

$u = new \ArrayIterator([1], \ArrayIterator::STD_PROP_LIST);
while($u->valid()){
    $x = 2 * $u->current() + 1;
    $y = 3 * $u->current() + 1;
    if($u->key() == $n){ // this is set elsewhere in the method; not really important for this example
        break;
    }
    $u->append($x);
    $u->append($y);
    $u->asort();
    $u->next();
}

 

Edited by maxxd

For makes copy of array and works off of the copy. Appended elements are added to array but not to the time copy. You cannot process the appended elements in the initial for loop.

 


<!DOCTYPE html>
<html>
<body>

<?php
$ptr = 0;
$colors = array("red", "green", "blue", "yellow"); 
$colors[] = 'pink';
foreach ($colors as $key => $value) {
  echo "$key <br>";
  echo "$value <br>";
  if ($key == 1) 
  { $colors[] = 'purple';
  }
}
echo '<br>';
print_r($colors);
?>  
    
</body>
</html>

 

Edited by sen5241b
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.