简体   繁体   中英

How to break while loop after condition meet in PHP?

I am printing $row->title when while loop meet some condition , but unfortunately without breaking it is printing all the results. Below is an example where 1st [_id] matching with last [_id] so it has to print only first value ['title'] which is MarQ, but it is printing both Marq and Jean.

My DB is like this -

    MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [_id] => MongoDB\BSON\ObjectID Object
                (
                    [oid] => 5fcbd8fbecf357fae06e2264
                )
    [title] = MarQ,
    [age] = 22
)
)

MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [_id] => MongoDB\BSON\ObjectID Object
                (
                    [oid] => 9s8393hf83959348200d
                )
    [title] = Bennet,
    [age] = 29
)
)

MongoDB\Model\BSONDocument Object
(
    [storage:ArrayObject:private] => Array
        (
            [_id] => MongoDB\BSON\ObjectID Object
                (
                    [oid] => 5fcbd8fbecf357fae06e2264
                )
    [title] = Jean,
    [age] = 20
)
) 

Here I am trying to Matching id if id matches it will print only first value in while loop.

but in my code it is printing all the values rather than only first value.

    foreach ($cursor as $row) {

         $i = 0;

      while ($i < count($row)) {

       $id   = isset($row[$i]["_id"]);

        $j = $i + 1;
while ($j < count($row) && $id == isset($row[$j]["_id"])) {
         $r++;
                   ?>
          <?php
         echo '<br>';
    ?>
     <?php

    $j++;
}
      $i++;
                    }
              }

 

(I have to do this only in while loop).

You can use break to break out of a loop. Documentation

 foreach ($cursor as $row) {

         $i = 0;

      while ($i < count($row)) {

       $id   = isset($row[$i]["_id"]);

        $j = $i + 1;
while ($j < count($row) && $id == isset($row[$j]["_id"])) {
         $r++;
         break;
                   ?>
          <?php
         echo '<br>';
    ?>
     <?php

    $j++;
}
      $i++;
                    }
              }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM