Reputation: 345
$cursor = $collection->find(/*...*/);
if (empty($cursor)) {
echo "List is empty!";
} else {
foreach ($cursor as $products) {
// do something
}
}
Unfortunately, empty
doesn't work on MongoDB results.
Upvotes: 0
Views: 1426
Reputation: 78984
I don't use MongoDB so I have updated based on the comment. Use $collection->count()
.
Check if it evaluates to a falsey value:
if(!$collection->count()) {
Or check for 0
:
if($collection->count() == 0) {
Or you could check empty
:
if(empty($collection->count())) {
Upvotes: 1
Reputation: 345
we can use the isDead()
method of the cursor
if (!$products->isDead()) {
// there are some results
}
See the relevant documentation on the PHP driver docs
Upvotes: 3
Reputation: 455
$cursor
is an object so it will always evaluate to true
and there is no $cursor->count()
in PHP driver for mongodb
Note that PHP driver for Mongodb is different from other drivers.
Try this:
if ($collection->count(...)) {
// note you must pass the query to the count function
$cursor = $collection->find(...);
foreach ($cursor as $products) {
}
} else {
echo "List is empty!";
}
OR:
$cursor = $collection->find(...);
if (!count($cursor->toarray())) { // convert to array and count it
echo "List is empty!";
} else {
foreach ($cursor as $products) {
}
}
Upvotes: 0