Anna Jeanine Anna Jeanine - 8 days ago 5
PHP Question

Catch undefined index from MongoDB document Laravel

Hi everyone! The documents within my MongoDB collection can differ. Some have an extra embedded document called

Additional_Information
. I would like the web browser to display a table of the information within the
Additional_Information
when this is available, and to ignore it when it's not found! This should be the easiest if-statement, but I can't get it to work. I have tried this code:

@if (is_array($document['Additional_Information']))
<li><a data-toggle="tab" href="#busco">Additional Information</a></li>
@endif


It does display the
Additional Information
tab when it is available. But when it is not, an
Undefined index: Additional_Information
it thrown! Does someone know how I can make this distinction between documents and catch when it's not there?

Answer

Use empty() instead:

@if (!empty($document['Additional_Information']))
      <li><a data-toggle="tab" href="#busco">Additional Information</a></li>
@endif

According to the documentation:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.