Signup/Sign In
PUBLISHED ON: AUGUST 12, 2021

How to populate dropdown list with array values in PHP?

Answer: Using foreach loop

We can populate the dropdown list with array values in PHP using the foreach loop. Here, populating the dropdown list means adding items to the list. In HTML, we add items to the dropdown list using the <option> tag, but in PHP, we can add items to the dropdown list using dynamically. We can make array elements as the items of the dropdown list using the foreach loop.

Example: Populating dropdown list using for each loop

In the given example, we have populated the dropdown list with array values in PHP using foreach loop.

<!DOCTYPE html>
<html>
<head>
	<title>Populate dropdown list with array values</title>
</head>
<body>
<form>
    <select>
        <option selected="selected">--Select--</option>
        <?php
        $proglang = array("C", "C++", "JavaScript", "PHP", "jQuery", "Java");
        
        foreach($proglang as $item){
            echo "<option value='strtolower($item)'>$item</option>";
        }
        ?>
    </select>
</form>
</body>
</html>

Output

dropdown

Apart from using foreach loop, we can also populate the dropdown list using the while loop.

Example: Populating dropdown list using while loop

In the given example, we have populated the dropdown list with an array values using a while loop.

<!DOCTYPE html>
<html>
<head>
	<title>Populate dropdown list with array values</title>
</head>
<body>
<form>
    <select>
        <option selected="selected">--Select--</option>
        <?php
            $proglang = ["C", "C++", "JavaScript", "PHP", "jQuery", "Java"];
            $arrayLength = count($proglang);
            
            $i = 0;
            while ($i < $arrayLength)
            {
                echo "<option>$proglang[$i] </option>";
                $i++;
            }
        ?>
    </select>
</form>
</body>
</html>

Output

dropdown

Conclusion

In this lesson, we have learned how to populate dropdown list with array values in PHP. So, we can populate the dropdown list with array values using foreach loop.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.