Always know where your towel is.

Generating HTML select with PHP foreach

I’m currently programming the update part of a simple CRUD user interface. This form loads up data relating to a product we’ve previously entered and lets you update its attributes. One of the fields required a dropdown box with a selection of available options with the current selected options being the first default selection.

While I know this isn’t rocket surgery, I took sometime to code it as efficiently as I could using a shorthand if/else statement embedded in the echo.

The final code

//$product_locations is 2d array pulled from the database, each row has two associations: id and title
//$product is another array pulled from the database that contains current attribute settings for the product

<select name="product[location_id]">
	foreach($product_locations as $product_location) :
		echo "<option value=\"".$product_location['id']."\" ".($product_location['id'] == $product['product_location'] ? "selected=\"yes\"" : "").">".$product_location['title']."</option>";

Here is the embedded shorthand conditional statement pulled out of the final code

.($product_location['id'] == $product['product_location'] ? "selected=\"yes\"" : "").

This could possibly be done more efficiently so if you have idea or comments, please share!

PHP Shorthand If / Else Example

Leave a Reply

Your email address will not be published. Required fields are marked *