The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Setting a HTML attribute in PHP

posted on 8.1.2023 by Below Surface in "PHP"

In this example we have the following HTML output from a .php file:

<select>
 <option value="one">One</option>
 <option value="two">Two</option>
 <option value="three">Three</option>
</select>

The .php file may look like this:

<select>
 <?php
  foreach ($numbers as $number) { ?>
   <option value="<?php echo $number; ?>">
    <?php echo $number; ?> 
   </option>
 <?php } ?>
</select>

To set one of the options as selected, simply define the number that should be selected and add this code to the option opening element:

<?php 
 $numberToSelect = "one";
?>
<?php echo $number == $numberToSelect ? 'selected="selected"' : '' ?>

The full code may look like this:

<?php 
 $numberToSelect = "one";
?>
<select>
  <?php
  foreach ($numbers as $number) { ?>
    <option value="<?php echo $number; ?>" <?php echo $number == $numberToSelect ? 'selected="selected"' : '' ?> >
      <?php echo $number; ?>
    </option>
  <?php } ?>
</select>

Tags:

php
html attribute

More posts of this category

Date creation and conversion in PHP

How to create and convert dates in PHP

PHP