How to populate dropdown list with array values in PHP

Topic: PHP / MySQL« Prev|Next »

Answer: Use the PHP foreach loop

You can simply use the PHP foreach loop to create or populate HTML <select> box or any dropdown menu form the values of an array.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>Dynamically Generate Select Dropdowns</title>
  • </head>
  • <body>
  • <form>
  •     <select>
  •         <option selected="selected">Choose one</option>
  •         <?php
  •         // A sample product array
  •         $products = array("Mobile", "Laptop", "Tablet", "Camera");
  •         
  •         // Iterating through the product array
  •         foreach($products as $item){
  •         ?>
  •         <option value="<?php echo strtolower($item); ?>"><?php echo $item; ?></option>
  •         <?php
  •         }
  •         ?>
  •     </select>
  •     <input type="submit" value="Submit">
  • </form>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.