Q:

How to populate dropdown list with array values in PHP

0

How to populate dropdown list with array values in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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. Let's try out an example and see how it works:

<!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){
            echo "<option value='strtolower($item)'>$item</option>";
        }
        ?>
    </select>
    <input type="submit" value="Submit">
</form>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get all the keys of an associative array in... >>
<< How to remove empty values from an array in PHP...