Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to be able to echo 1 and 2 with an array_push in the same foreach loop of that array.

<?php
$arr = array('1');

foreach ($arr as &$arr_number) {
   echo "$arr_number\n"; //this print 1
   array_push($arr, '2');
}

foreach ($arr as &$arr_number) {
   echo "$arr_number\n"; //this print 1 and then 2
}
?>

EDIT: Solved it myself by not using a foreach but a while loop

    <?php
    $arr = array('1');

 while ( list($key, $value) = each($arr) ) {
    echo "$value\n";

    if ( !in_array('2', $arr) ) {
       array_push($arr, '2');
    }
 }
 ?>
share|improve this question
1  
unable to understand question. can you please elaborate? –  Echo Mar 4 at 7:28
1  
What you're trying to do? –  hindmost Mar 4 at 7:29
1  
What is the aim for using references in your code? –  zerkms Mar 4 at 7:30
 
@echo: echo 1 and 2 –  Zurd Mar 4 at 7:36
 
@zerkms: yeah, probably no point in using references... doesn't matter, code still doesn't work with foreach without references –  Zurd Mar 4 at 7:42
add comment

1 Answer

I need to be able to echo 1 and 2 with an array_push in the same foreach loop of that array.

Implode it.

<?php
$arr = array('1');

foreach ($arr as &$arr_number) {

   array_push($arr, '2');
   echo implode(' ',$arr); //"prints" 1 2
}
share|improve this answer
 
would that not be an infinite loop ? –  KarelG Mar 4 at 7:33
2  
How would it ? FYI, Demo –  Shankar Damodaran Mar 4 at 7:34
 
you're pushing an variable into an array which you're looping through. I thought that the iterator would detect the newly added item and thus continuing the loop. But it's an instance at that moment. My excuses for my confusion. –  KarelG Mar 4 at 7:37
 
@KarelG The implode function above simply concatenates all the array values together with a space. It won't affect the loop. Also the iterator does not detect the newly added value which is why the OP is receiving only 1 as output. –  I Can Has Cheezburger Mar 4 at 7:37
 
@KarelG No, it's not. see the first answer of stackoverflow.com/questions/2348077/… –  Hereblur Mar 4 at 7:39
show 6 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.