How do I check if MongoDB result is empty in PHP - php

$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.

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

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())) {

$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) {
}
}

Related

how to use the in_array function, that is storing a variable from an input field

I am trying to check if a value already exists in an array with the in_array function but it is not working. When i assign the $companyalis variable to a string, lets say "Bay" it works. Please how can i solve this issue. Note: the $alias contains a value from an input field.
$companyalis = strtoupper($alias);
if (is_array($responses)) {
$data = [];
foreach ($responses as $val) {
$data[] = $val['alias'];
}
if (in_array($companyalis, $data)) {
echo "Alias is already defined";
}else {
echo "Alias does not exist";
}
}
}
If I understood your question correctly
$companyalis = strtoupper($alias);
if (is_array($responses)) {
$data = [];
foreach ($responses as $val) {
$data[] = $val['alias'];
}
if (in_array($companyalis, array_values($data))) {
echo "Alias is already defined";
} else {
echo "Alias does not exist";
}
}
$aliasList[] = "Other";
$aliasList[] = "manY";
$aliasList[] = "someTime";
$test = "Many";
if(in_array(strtolower($test),array_map('strtolower',$aliasList))) echo "Find";
else echo "Not Find";
I think this code can help you if I understood your question correctly.
The principle is to pass the search string in lowercase as well as all the elements of the array. Via the "strtolower" function applied thanks to "array_map" (thus on the whole array)

For each loop in PHP erroring out "invalid argument supplied"

I'm trying to get this function to work but for some reason it errors out on the foreach line saying there is an invalid argument.
$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
echo "<p>No Scores</p>";
} else {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
}
The error I get is: PHP Warning: Invalid argument supplied for foreach()
For example, empty('') would also be true.
I would recommend to check is_array($scores) && count($scores) instead of empty(), to make sure the api returned useable output (an array) and that this contains elements (count() > 0 which is true).
$scores = TESTAPI::GUL($user->ID);
if (is_array($scores) && count($scores)) {
foreach ($scores as $score) {
echo "<p>".$score."</p>";
}
} else {
echo "<p>No Scores</p>";
}
Try this -
foreach ((array) $scores as $score) { ...
Looks like $scores is neither an array nor an object...

Faster way to see if an array contains values besides the one specified

I have an array where each element has a subarray with multiple Ids. When looping through the array, I'd like to check if the subarray has any elements besides a given one.
For example, I'd like to echo 'Yes' whenever one of the subarrays has any ids other than 'TESTID'.
I can do this by looping through the subarray, but I'd like to know of a way that doesn't require double loops.
Here's the current code:
foreach ($elements as $element) {
...
if (besidesInArray('TESTID',$element['ids'])) {
//operations
} else {
//element only has 'TESTID'
}
...
}
...
function besidesInArray($needle, $haystack) {
foreach ($haystack as $hay) {
if($hay != $needle) {
return TRUE;
}
}
return FALSE;
}
While this code works, I'd like to see if there's a more elegant solution.
You can use in_array() function to achieve this
foreach($array as $key => $subarray)
{
if(in_array("TESTID", $subarray))
{
//found
} else {
//not found
}
}
preg_grep for TESTID but invert the grep so that it returns entries NOT matching.
foreach($array as $subarray) {
if(preg_grep("/TESTID/", $subarray, PREG_GREP_INVERT)) {
echo 'Yes'; //others found
}
}
TESTID could be a var instead. Man I love some preg_grep!
find = implode(')|(',$mypatternarray);
find.="(".find.")";
foreach($subarray as $subar){
if(preg_match("find",$subar)>0)){
echo "id found";
}
}

Parsing decoded JSON in PHP

I have managed to decode some JSON in PHP successfully (not as painful as I thought), but it's been such a long time since I've done any real PHP, my brain has drawn a blank on the following.
The decoded json looks like this
[Array]
item {
[0]
{
[live]=>
[name]=>Paul
[value]=>10
}
[1]
{
[live]=>1
[name]=>Fred
[value]=>32
}
and so on
The problem I'm having is this - I'm trying to iterate through the structure to test first if live==1 and then if it's the first live name, to output it as a selected value to a HTML drop down.
I'm currently trying like this
$t = 0;
$count = 0;
foreach($decode['items'] as $option=>$value)
{
print_r("option = $option\n");
if ($option=>isLive == 1)
{
print_r("isLive is true for $option[$count]['names']\n");
if ($t == 0)
{
echo "<option value=$option[name] selected>$value[name]</option>";
$t = 1;
}
else
echo "<option value=$option[name]>$value[name]</option>";
}
else
{
print_r("isLive is false for $option[$count]=>name\n");
}
$count++;
}
the problem is that I don't seem to be able to get the if statement correct for this to work. This is probably a seriously simple problem and will no doubt make me face palm, but I could do with a pointer in the right direction here!
If the json is like you showed us you could not iterate over anything with your foreach because your array does not contain a key named items.
Using the provided structure this should do the trick:
foreach($decode["item"] as $item) {
if($item->live == 1) {
...
} else {
...
}
}
If $item is not an object use $item['live'] instead.
P.S.: You should really turn error_reporting on. $option=>isLive is no valid syntax.
$t = 0;
$count = 0;
$arr = json_decode($json,true);
foreach($arr as $key=>$val)
{
print_r($key);
if($val['live'])
{
if($t == 0)
{
echo '<option value='.$val['name'].' selected>'.$val['name'].'</option>';
$t = 1;
}
else
{
echo '<option value='.$val['name'].'>'.$val['name'].'</option>';
}
}
else
{
echo $key.' not printed cause it hasn\'t live set to true';
}
$count++;
}

PHP Looping through entire multidimensional array but only giving one result back

I have got an multidimensional array on which I run a foreach loop.
I basically want to see if I've got the country_url stored in an database. If it is in the database then I'll echo "exists" but if it doesn't then I want to echo "doesn't exist". I don't want it to tell me for each array if it exists or not, but I want the foreach loop to tell me whether the country_url exists in one of the arrays or not.
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
echo "exists";
} else {
echo "doesn't exist";
}
}
Would anyone be able to help me out with this?
Try this:
$exist = false;
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$exist = true;
break;
}
}
if ($exist){
echo "exists";
} else {
echo "doesn't exist";
}
You could store a variable and then use break to terminate the loop once the item is found:
$exists = false;
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$exists = true;
break;
}
}
if ($exists) {
echo "Success!";
}
This should work:
$text = "doesn't exist";
foreach ($countriesForContinent as $country) {
if ($country['country_url']==$country_url) {
$text = "exists";
break;
}
}
echo $text;
As an alternative to the other answers, you could do the following:-
echo (in_array($country_url, array_map(function($v) { return $v['country_url']; }, $countriesForContinent))) ? 'exists' : 'does not exist';
This is probably slightless less efficient though as it will essentially loop through all $countriesForContinent rather than finding a match and break[ing].

Categories