Open In App

How to Populate Dropdown List with Array Values in PHP?

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We will create an array, and then populate the array elements to the dropdown list in PHP. It is a common task when you want to provide users with a selection of options. There are three approaches to achieve this, including using a foreach loop, array_map() function, and implode() function. Here, we will explore each approach with detailed explanations and code examples.

Approach 1: Populate Dropdown List with Array Values using foreach Loop

You can use a foreach loop to iterate over an array of elements and populate the dropdown list with its values.

PHP
<?php

$options = array(
    "HTML",
    "CSS",
    "JavaScript",
    "PHP"
);

?>

<select>
    <?php foreach ($options as $option): ?>
        <option value="<?php echo $option; ?>">
            <?php echo $option; ?>
        </option>
    <?php endforeach; ?>
</select>

Output:

dropdown-list-php

Approach 2: Populate Dropdown List with Array Values using array_map() Function

The array_map() function can be used to apply a callback function to each element of an array. You can use it to generate the <option> tags for the dropdown list.

PHP
<?php $options = array(
    "HTML",
    "CSS",
    "JavaScript",
    "PHP"
); ?>

<select>
    <?php echo implode(array_map(function($option) {
        return "<option value=\"$option\">$option</option>";
    }, $options)); ?>
</select>

Output:

dropdown-list-php

Approach 3: Populate Dropdown List with Array Values using implode() Function

You can also use the implode() function to concatenate the array values into a string and then use it to populate the dropdown list.

PHP
<?php $options = array(
    "HTML",
    "CSS",
    "JavaScript",
    "PHP"
); ?>

<select>
    <?php echo "<option>" 
        . implode("</option><option>", $options) 
        . "</option>"; 
    ?>
</select>

Output:

dropdown-list-php


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads