Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push into array while it is being looped

Here's a snippet of my code. I understand that it is generally advised against to modify an array whilst it is being looped, however in this scenario I think it is the right thing to do and saves resources.

$levels = array($post);
foreach ($levels as $level) {
    $next_sibling = get_next_sibling_page($level);
    if ($next_sibling) {
        $next_page = $next_sibling;
        break 1;
    } else if ($level->post_parent) {
        array_push($levels, get_page($level->post_parent));
    }
}

The idea is that the foreach would reiterate with the pushed value if ($level->post_parent), I can see that the if statement is resolving to true and the array is being pushed to however the foreach does not reiterate and only runs the one time.

Does anyone know how I can recursively continue my foreach until $level->post_parent resolves to false?

like image 613
George Reith Avatar asked Nov 22 '25 06:11

George Reith


1 Answers

To modify array which is being used in foreach pass array by referance.

foreach (&$levels as $level) {
   .....
}
like image 185
dpitkevics Avatar answered Nov 24 '25 18:11

dpitkevics



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!