Search⌘ K
AI Features

Adding a Select Element to the Form

Explore how to add a select element to a PHP form to provide user choices, including displaying selected images. Understand processing submitted data, maintaining form state with the selected attribute, removing code duplication by looping through options, and ensuring HTML output remains clean. This lesson helps you implement dynamic and user-friendly form controls in PHP applications.

Giving a choice to the user

Consider we want to give the user the option to select which picture to show. We should start with downloading another picture from the internet and saving it to the public/. For this exercise, a picture of an apple on a stack of books is chosen. It is saved to public/apple.jpg.

Let’s give the user a choice by adding a select element to the form:

PHP
// ...
<div>
<label for="picture">
Select a picture:
</label>
<select name="picture" id="picture">
<option value="cat.jpg">Cat</option>
<option value="apple.jpg">Apple</option>
</select>
</div>
// ...

We are going to use the script to display pictures of apples in addition to kittens. So, we should rename the file to something more generic. Let’s change it to pictures.php (don’t forget to update /random.php, too because it still refers to /kittens.php). In the browser, go to http://APPLINK/pictures.php and verify that the new form element shows up.

You don’t have to open any URL as we have already set things up for you. Press the Run ...