4

How can I accomplish this in php? there are cases where I need to push more elements to the array that i'm looping through so they also get looped through:

$j = array(1,2,3);
foreach ($j as $i)
{
    echo $i . "\n";
    if ($i <= 3)
        array_push($j, 5);
}

should print 123555 but it stops at 123.

is there a way around this in php?

0

4 Answers 4

4

foreach works on a copy of the array, not the original array (under certain conditions). That's why you're not seeing the changed reflected in the loop.

You will get the expected output when you loop by reference:

foreach ($j as &$i)
{
   // ...
}

Output:

1
2
3
5
5
5
Sign up to request clarification or add additional context in comments.

Comments

3

Add & to pass the reference. Default a value (copy of $j) is passed.

$j = array(1,2,3);
foreach ($j as $i=>&$v)
{
    echo "$i=>$v\n";
    if ($i <= 3)
        array_push($j, 5);
}

Comments

2

PHP does not support this. From the manual:

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

http://php.net/manual/en/control-structures.foreach.php

However, this code will work, although I would not rely on this based on what the manual said.

<?
header( 'content-type: text/plain' );

$j = array(1,2,3);

foreach ($j as &$v )
{
    echo "$v\n";
    if ($v <= 3)
    {
        array_push($j, 5);
    }

}

Comments

1

Why don't you try while:

$i  = 0;
$j  = array( 1, 2, 3 );

while ( count( $j ) )
{
    echo array_shift( $j );

    if ( $i++ <= 3 )
    {
        array_push( $j, 5 );
    }
}

Comments

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.