Chris Chris - 1 year ago 93
PHP Question

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>
<? } ?>

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

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

<optgroup label="Green Backgrounds">

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

<optgroup label="Blue Backgrounds">

Answer Source


<select name="backgroundList" id="backgroundList">
$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>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download