MongoDB Tutorial Part 6.5: Fixing itemView.php

I was working on the next part of this tutorial when I noticed a tiny mistake I made in itemView.php. If you look back at the design document, weapon special attributes are optional. But the code that prints out weapon type treasures acts like every treasure is going to have at least one special attribute. Find this code in itemView.php:

 

  case 'Weapon':
      echo '<b>Bonus:</b> '.$itemAttributes['Bonus'].'<br/>';
      echo '<b>Special Attributes:</b>';
      echo '<ul>';
      foreach($itemAttributes['Special Attributes'] as $specialAttribute){
          echo "<li>$specialAttribute</li>";
      }
      echo '</ul>';
      break;

Notice how it just jumps right into the foreach loop of $itemAttributes[‘Special Attributes’]? If a particular weapon doesn’t have any special attributes that information won’t exist and we’ll get a minor error. So let’s fix it by changing it to something more like this:

 

case 'Weapon':
    echo '<b>Bonus:</b> '.$itemAttributes['Bonus'].'<br/>';
    if( !empty($itemAttributes['Special Attributes']) ){
        echo '<b>Special Attributes:</b>';
        echo '<ul>';
            foreach($itemAttributes['Special Attributes'] as $specialAttribute){
                echo "<li>$specialAttribute</li>";
            }
        echo '</ul>';
    }
    break;

 

Now the code will only try to print special attributes when there are special attributes to print and won’t throw errors when it runs into a boring no-attribute weapon.

 

That’s all for this mini-update. Tutorial 7 coming soon!