New MongoDB\BSON\ObjectId() breaks PHP foreach loop

PHP 8.x
MongoDB 4.x

I have a page where people can check some checkboxes to delete specific items.
The values contain the _id as a string.
It’s then sent to the server where I do a foreach() loop on these checkboxes where I build an array and use new MongoDB\BSON\ObjectId() to turn it back to the native id.

For some reason the foreach loop is run once and the script also stops but no fatal error.
If I remove the new MongoDB… and just add the checkbox values in the array it works.

This is the code:

$arr = array();
foreach($_GET['items'] as $vals) {
      if(!empty($vals))

         {
        $arr[] = new MongoDB\BSON\ObjectId($vals);
         }
     }

If I dont use the foreach loop and just for testing add 5-6 items in the array myself it does work.
How can I solve this and why is it doing this.

Found the solution, very weird.
If i add the new MongoDB… in the foreach directly it fails, if I call a function that does exactly the same it does work:

$arr[] = mongoid($vals)

function mongoid($v)

   {
   return new MongoDB\BSON\ObjectId($v);
   }

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.