Applying an if statement to a foreach loop

Tuesday, May 26, 2015 - 22:00

I was approached today to hide a table column when a certain item type was being displayed .For our purposes lets call them guitars and drums

As part of the table, I was looping through an array to print out a list of links.to different types of guitars. For Drums, I didn't need that column

The variable we'll call, $instrument_type

First lets just look at the loop

<td>
<?php
if ($instrument_type == 'guitar' )
 foreach($instrument => $key => $value)
 print '<a href="/guitar-type/'.'$value">$value</a><br/>";
?>
</td>

The important thing to note here is that you can easily put an if statement right before the foreach loop. I found this through experiementation because I could not find it easily online anywhere.