Skip to content
Advertisement

Select Dropdown PHP foreach loop with ‘optgroup’ options

I have a dropdown menu with a PHP ‘foreach’ that I loop through to populate the select options. This works well. However, what I’d like to do is have various sub labels using the “optgroup” option. In my returned array, I have a “type” of “blue”, “green” and “red”. How can I split the select options up into groups based on the $album[‘type’]?

This is the code I have:

$query = mysql_query("SELECT * FROM background_albums);
$albums = array();
while($row = mysql_fetch_assoc($query)) {
    array_push($albums, $row);
}

<select name="backgroundList" id="backgroundList">
  <? foreach($albums as $album) { ?>
    <option value="<?=($row['id']);?>"><?=$row['title'];?></option>
  <? } ?>
</select>

This is the kind of thing I’d like to achieve within the foreach loop:

if ($album['type'] == 'green')...

<optgroup label="Green Backgrounds">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
</optgroup>

if ($album['type'] == 'blue')...

<optgroup label="Blue Backgrounds">
      <option>5</option>
      <option>6</option>
      <option>7</option>
      <option>8</option>
</optgroup>

Advertisement

Answer

Try

<select name="backgroundList" id="backgroundList">
<?php
$album_type = '';
foreach ($albums as $album) {
  if ($album_type != $album['type']) {
    if ($album_type != '') {
      echo '</optgroup>';
    }
    echo '<optgroup label="'.ucfirst($album['type']).' Backgrounds">';
  }
  echo '<option value="'.$album['id'].'">'.htmlspecialchars($album['title']).'</option>';
  $album_type = $album['type'];    
}
if ($album_type != '') {
  echo '</optgroup>';
}
?>
</select>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement