Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach SplPriorityQueue - can't find the elements

I have the following code:

    $friendsOrdered= new SplPriorityQueue();
    ... // Code to fill up the priority queue
    print_r($friendsOrdered);
    $i = 0;
    foreach($friendsOrdered as $f) {
    }
    echo "<br><br>";
    print_r($friendsOrdered);

When I look at the output of the prints I can see that after the loop the priority queue is empty. Is there a way of stopping the foreach from removing elements?

Thanks!

like image 743
user973758 Avatar asked Feb 15 '26 01:02

user973758


1 Answers

You cannot stop the loop from dequeuing elements, as that is the nature of the data structure. You could, however, create a copy of the object before the loop so your data isn't lost:

$friendsOrdered_copy = clone $friendsOrdered;
foreach($friendsOrdered_copy as $f) {
    // ...
}

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!