2

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');
    }
 }
 ?>
4
  • 1
    unable to understand question. can you please elaborate? Commented Mar 4, 2014 at 7:28
  • 1
    What you're trying to do? Commented Mar 4, 2014 at 7:29
  • 1
    What is the aim for using references in your code? Commented Mar 4, 2014 at 7:30
  • @zerkms: yeah, probably no point in using references... doesn't matter, code still doesn't work with foreach without references Commented Mar 4, 2014 at 7:42

1 Answer 1

3

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
}
10
  • 1
    would that not be an infinite loop ? Commented Mar 4, 2014 at 7:33
  • 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. Commented Mar 4, 2014 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. Commented Mar 4, 2014 at 7:37
  • @KarelG No, it's not. see the first answer of stackoverflow.com/questions/2348077/… Commented Mar 4, 2014 at 7:39
  • @KarelG yes that would be an infinite loop, I had to kill PHP :) I added the check in_array to make it work Commented Mar 4, 2014 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.