Home » Php » Inserting Php code inside html tag by php

Inserting Php code inside html tag by php

Posted by: admin February 25, 2020 Leave a comment

Questions:

In my html/php file I have the following tag:

<select name="seitJ">
    <option value=20 <?php if ( $_GET["bisJ"]==20 ) echo("selected"); ?> >2020</option>
    <option value=19 <?php if ( $_GET["bisJ"]==19 ) echo("selected"); ?> >2019</option>             
    <option value=18 <?php if ( $_GET["bisJ"]==18 ) echo("selected"); ?> >2018</option>
</select>

What I want is a php code which updates this code every beginning of a new year automatically. My problem are NOT the date- functions but how to insert the php code contained in the tags. I think I would have to include php code inside php code which I know doesn’t work.

How to&Answers:

This should do what you want:

Essentially I am setting the year to the current year (2020), setting the target year to the current year minus 4 years (2016) and I am looping through, reducing the year by 1 each iteration until we reach our target year.

<select name="seitJ">
    <?php
    $year = date('Y');
    $target = $year - 4;

    for($i = $year; $i > $target; $i--) {
        $digits = substr($i, 2);
        $selected = ($_GET['bisJ'] == $digits ? 'selected' : '');
        echo '<option value="' . $digits . '" ' . $selected . '>' . $i . '</option>';
    }
    ?>
</select>

Resources:

substr()

for()

Answer:

You can try this

<select name="seitJ">
<?php 
   for($i = 2000; $i < date('Y'); $i++){
      echo "<option value=<?php echo $i; (date('Y') == $i) ? echo selected : ''?> >$i</option>";
   }
?>
</select>

The date(‘Y’) will get you the current year so it will update automaticly.
And keep in mind that it’s a good practice to create a loop instead of writing the values one by one.