Php foreach loop into select & remove blank options

Hello, I’m populating a select with data from my database table. In the table I have four columns some of the columns have lots of data others don’t.

Now I’m only extracting them by categorys to the selects, but I’ve noticed when you open the select that blanks from table also creates and option for it.

This is the code for better understanding:

      <select class="form-select w-75" name="projecttype" required>
        <option></option>
        <?php foreach($result as $data): ?>
          <option value="<?php echo $data['projectoptions'] ?>"><?php echo $data['projectoptions'] ?></option>
        <?php endforeach ?>
      </select>

the output:

I got lots of empty white space in the select.

I’ve red about range(), but I think I’m not understand it correctly. Since I know the amount of data in that column is 8. How do I set it to stop at 8 and not continue with the blank spaces?

Ignoring that the data doesn’t seem to be normalized, use array_column() to get a specific column of data out of the $data array, then use array_filter() to remove empty values, before looping over the values.

1 Like

i’d throw a unique in there too… or into the query to begin with… or… how about a WHERE NOT NULL in the query too?

1 Like

Thank a lot guys, your answers solved it nicely.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.