[PHP] Easiest way to create a HTML Select/Combo box

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
Okay, now I think everyone who does HTML thinks that making a Select/Combo box is a complete and utter pain in the arse, having to retype the same things over and over again and change the text between <option> and </option>, well, in this tutorial I am going to show you a really quick way to do this in PHP within 2 minutes.

First off, we need to decide what options are going to be available in the Select/Combo box, I'm going to have singers names, so I am going to declare them in an Array like so:

PHP:
$options = array( 'Eminem', 'D12', '50 Cent', 'Jay-Z', '2Pac' );
There we go, now we have our singers names set up, so now we have to make sure that PHP enters them into a select/combo box

Now we need to set up the Select box, to do that, type this:

PHP:
echo '<select name="singers">';
Now I am going to comment almost every line of code so you understand what is going on.

PHP:
foreach( $options as $option )
{
This gets each of the strings set between the apostrophise in the $options array and changes them to the variable $option.

Now we want to get it to echo them into <option></option> HTML tags, so to do that we do this:
PHP:
   echo '<option value=' . $option . '">' . $option . '</option>';
Now to end the code we type this:
PHP:
}
//now end the select box:
echo '</select>';
There, we have successfully entered each of the singers names into a select box instead of having to retype everything over and over again!

Here is the full code:

PHP:
<?php
$options = array( 'Eminem', 'D12', '50 Cent', 'Jay-Z', '2Pac' );
echo '<select name="singers">';
foreach( $options as $option )
{
   echo '<option value=' . $option . '">' . $option . '</option>';
}
//now end the select box:
echo '</select>';
?>
Yet again, I'm aware that this isn't the most detailed/understandable tutorial as I am not good at explaining things, but I hope this helped anyway! :)
 
Status
Not open for further replies.

Users who are viewing this thread

Top