PHP foreach loop to populate dropdown list with values from an array of arrays

PHP foreach loop to populate dropdown list with values from an array of arrays

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Automating Dropdown Population in PHP

Hardcoding every <option> tag for a dropdown list is a maintenance nightmare. If your database changes or if you need to add new classes, you are forced to manually update your HTML file. The solution is to iterate through the data structure using a loop, but doing so requires careful handling of variables inside HTML tags to ensure the output renders correctly.

In your specific case, you have retrieved data from the database using fetchAll(). The resulting $names variable is an array of arrays:

Array ( [0] => Array ( [name] => Web Design ) ... )

Each element in $names contains a single key, ['name'], holding the string value you want to display. While your current approach works for ten items, it breaks down as soon as the dataset grows beyond what you can type into the editor.

The Foreach Pattern

To replace hardcoded options with dynamic ones, use a foreach loop. This construct iterates over each element in the $names array, assigning the current item to a variable (conventionally $item). Inside the loop, you can generate the HTML for a single option tag and echo it into your output buffer.

Here is how the logic translates into code:

$names = $db->fetchAll("select `name` from `classes`");

echo '<label for="per1"></label>';
echo '<select name="per1" id="per1">';

// Always include a default selection before looping, or handle it inside the loop
echo '<option selected="selected">Choose one</option>';

foreach ($names as $item) {
    // Access the 'name' key from the current array item
    echo '<option value="' . htmlspecialchars($item['name']) . '">' 
         . htmlspecialchars($item['name']) . '</option>';
}

echo '</select>';

Handling Variable Expansion in HTML

A common stumbling block when mixing PHP and HTML is how variable expansion works. You cannot place a PHP variable directly inside an HTML attribute string without concatenation. The syntax value="$names[0]['name']" is invalid because the browser treats $ as part of the literal string, not code.

You must use dot concatenation (. $variable) or curly braces {} to inject the value:

// Correct
echo '<option value="' . $item['name'] . '">' . $item['name'] . '</option>';

// Incorrect (treated as literal text by browser)
echo '<option value="$item[name]">' . $item['name'] . '</option>';

Security and Data Integrity

When dynamically generating HTML based on database content, you are responsible for preventing Cross-Site Scripting (XSS). If a class name in your database contains malicious script tags, such as <script>alert('XSS')</script>, a naive echo statement will render that script when the page loads.

The htmlspecialchars() function converts special characters like <, >, and & into their HTML entities (&lt;, &gt;, &amp;). This ensures that even if the database contains user-generated content, it is displayed as plain text rather than executable code. It is a mandatory step when populating dropdowns from external data sources.

Alternative: Using Laravel Helpers

If you are working within the Laravel framework, you might prefer using Blade templates over raw PHP mixed with HTML. This separation of concerns keeps your logic clean and your views readable. You can pass the $names array to the view and loop directly in the template:

<select name="per1" id="per1">
    <option selected="selected">Choose one</option>
    @foreach($names as $item)
        <option value="{{ old('per1', $item['name']) }}">
            {{ $item['name'] }}
        </option>
    @endforeach
</select>

Blade automatically handles escaping by default, removing the need to manually wrap values in htmlspecialchars(). Additionally, the old() helper function preserves form data if validation fails, allowing you to pre-select an option based on a previous submission. This approach is particularly robust for larger applications where managing state across requests is critical.

Performance Considerations

While iterating over a small array of ten items has negligible performance impact, this pattern scales efficiently regardless of the dataset size. Whether you have 20 classes or 20,000, the foreach loop executes in linear time relative to the data count. The overhead of concatenating strings inside a loop is minimal compared to the cost of database queries. If you find yourself with massive datasets that require complex rendering logic per item, consider caching the rendered HTML string or using a template engine like Laravel Blade to reduce CPU cycles during page generation.

Ultimately, moving from hardcoded HTML to dynamic loops makes your application resilient to data changes and significantly reduces the risk of human error when updating the interface.

Our network