php in select>options


I'm just learning php (by force), but am pretty well versed in html and css. I did not rite the following code and I'm not sure how to pull out the php in the following in order to make the page validate.

         <td width="15%"><b><b>Priority</b></td>
         <select name="priority" size="1" value="priority">
            <option value=""
<?php if ($row['priority'] == "") echo " selected";?>
            <option value="Normal"
<?php if ($row['priority'] == "Normal") echo " selected";?>
            <option value="Elevated"
<?php if ($row['priority'] == "Elevated") echo " selected";?>
            <option value="STAT"
<?php if ($row['priority'] == "STAT") echo " selected";?>

The idea is to prefetch the "priority" info and populate the drop down with that. Afterwards, the user can change the value and once submitted, the value will change in the database. Any pointers would be appreciated - and thanks in advance.

Who is Participating?
There are several answers for the core of the problem :)

1. You DON'T need a validator. (Many ppl will disagree here but believe me: if you know the standards, you don't have to follow them(

2. This code is not very nice and the reason is NOT what the validator says.  Your future eyes are the real validator - this code will look like a mess when you look at it a few months later.

3. If you're determined to force your code thru Tidy (or whatever you validate with), consider using a javascript solution to make the default item "selected".  jQuery is a good friend when you need such things.  You'll still need a <?php .......?> tag but as xmediaman said, a well behaving validator SHOULD skip php codes.

4. If it doesn't, try validating the RESULT that the browser gets - use "view source", copy it to a textfile, and validate that.  After all, THAT is what should be valid, not your PHP source.

Now here's a function that I'm using (for years) to create dropdowns.

function optionlist($t,$default="",$lf="") {
	foreach ($t as $n=>$x) {
		$sel=($n==$default?" selected":"");
		$out.="<option value=\"$n\"$sel>$x$lf";
	return $out;

Open in new window

Use it like this:

<select .............>
<?php optionlist($myArray,$defaultItem); ?>

Open in new window

...where $myArray is an array with key=>value pairs of the list contents and $defaultItem is the key of the element that should be selected initially.

Just an example, really.  You'll find yourself writing such helpers for yourself and use them instead of HTMLing repetitive things directly.  That's the way of the samurai.
Kim WalkerWeb Programmer/TechnicianCommented:
The php code should be ignored for HTML validation, but it is the un-indented lines that begin with "<?php" and end with "?>".
i think that if you will be working with php, you need to change to a different validator. taking out php and then putting it back in is a pain.
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.


<select .............>
<?php print optionlist($myArray,$defaultItem); ?>

is the proper way to use it.  optionlist only returns the HTML string.
rather than simply echoing 'selected' to ensure the code validates should you not use


Open in new window

For example:

<option value="STAT" 
<?php if ($row['priority'] == "STAT") echo ' selected="selected"';?>

Open in new window

From testing if you simply echo 'selected' you receive the following validation error:

"SELECTED" is not a member of a group specified for any attribute

Open in new window

However using selected="selected" solves the error.

Hope that helps.


Ray PaseurCommented:
You might want to get this book and give yourself a month or so to work through the problems and examples so you can learn the basics of PHP.  It's very readable with excellent examples and a code library you can download for your own use.  Now in its fourth printing, it has been a permanent part of my professional library since Edition One.

The PHP site has the online introductory tutorial -- that will be helpful, too.

What the code posted with this question appears to be doing goes something like this...

We have already made a query and retrieved a row from the data base.  That row is an associative array named $row.  While there may be other things in $row, we assume that there is a value in $row["priority"] which may be NULL (empty string) or one of Normal, Elevated or STAT.  The combination of the HTML and PHP would work together through the PHP parser.  The PHP if() statements would be used to determine what HTML should be generated.  The pre-selected option in the HTML form select control would be determined by the contents of $row["priority"].

If the code you posted is in a file named like thing.html you might want to try running it in a file named like thing.php

Best of luck with your studies, ~Ray
Olaf DoschkeSoftware DeveloperCommented:
Like dkellner already said a good validator should skip PHP code in it's validation. The other very obvious way of getting rid of the php code is executeing it. If you eg feed an online HTML validator with the url of the php skript the php executes and the resulting html is validated.

The problem is, you can't really predict the html in general, or create it by just skipping the php. A more complex php will have loops and if statements and other program flow mechanism, that by condition create some html by other conditions other xml. In your case either one priority option will be marked selected. To validate html output in this case would need running the php with all possible $row['priority'] values to get all the different outputs. This would be called code coverage tests, to see if the code runs in each of the different branches that can run.

PHP in this way is not the preferenced way, as it mixes HTML with code. That was the original intent of the php inventor, but it turns out, not just in HTML/CSS seperation of concerns is better. Ray already pointed you to general material about php, dkellner already gave you the good advice to seperate the functionality into functions you call. This makes the php less convoluted, on the other side in his case wht remains is just the <select...>php</select>, which by itself also doesn't validate, if you just remove the php code.

It's really a situation where you can't have the pie and also eat it. If you want dynamic creation of html you don't have static hml you can validate, your html variants multiply by the number of different ways the php execution can go, but you can take one case as a test sample, once you also verify, that the php skript behaves in the similar way always. In your pecial case always one of the selection options is selected, or none, but never two.

Take a look here:
They describe the hard problem in detail and offer an on-the-fly validation here:

You'd put that into a debug version of your php site and every php script outputting html will also output a temp file .validate.html which then is validated. During a tet phase you can check if your php misbehaves in some situations.

In very short summarized:
1. You need to extend your toolbelt, if you extend your static HTML to be dynamic, be it by php or AJAX/javascript or anything else.

2. The seperation approach you could go instead or on top of this, is in parallel to the separation of html and css you already should be familar with, you'd seperate the php logic from the html by defineing templates. The php will not put together html piece by piece or embed itself into the html, the html templates would have placeholders the php script will then replace, this makes the templates easier to validate.

finally, you're not alone: See this discussion:

Users are going both the hard route trying to finetune what validator should validate or the simple route and turning it off. If you'd ask my personal oppinion, the html validation is not the main concern, even not for static html. Even if html validates to the rules, the browsers don't necessarily display the html the same way. And that also goes for dynamically created html.

Bye, Olaf.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.