-1

I am trying to display a drop down with 1 - 100, sounds simple, and yes, I am a little new... but what am I missing? I can get it to display 50 different dropdowns with a single number in it and the other 50 numbers show as labels.

if (this > that) {
for ($i=1; $i<=100; $i++)
{
    echo '<select name="numberCounter" id="numberCounter">

    <option value="'.$i.';">'.$i.'</option>';
   }
}


echo '</select>';
JerryH
  • 29
  • 7

2 Answers2

1

Your code should look similar to this:

if(this > that) {
    echo '<select name="numberCounter" id="numberCounter">';
    for ($i=1; $i<=100; $i++)
    {
        echo "<option value='{$i}'>{$i}</option>";
    }
    echo '</select>';
}

If you notice, the start of the select element is outside of the loop, therefore creating a single select element with the options inside of it.

I've also used what is called Complex Expressions in this code, which is the curly brackets ({}). This is basically string concatenation, you just have to make sure the string itself is surrounded by double quotes. You could optionally drop these entirely, but I believe it helps readability. You could, for example, make it echo "<option value='$i'>$i</option>";


It may be a good idea for you to also seperate your HTML from your PHP a little bit. This may look a little bit messier at first, but it really helps if you are using an IDE as this will still allow HTML syntax highlighting.

if(this > that) {
    ?>
    <select name="numberCounter" id="numberCounter">
        <?php
        for ($i=1; $i<=100; $i++)
        {
            ?>
            <option value="<?=$i;?>"><?=$i;?></option>
            <?php
        }
        ?>
    </select>
    <?php
}

In this code snippet I use PHP echo short syntax (<?=$variable;?>) which really should only be used if you are using a PHP version >= 5.4. If you are using a version lesser than that, you should really consider updating, but if you can't, then you could just use regular syntax (<?php echo $variable; ?>).

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
0

You have to watch your use of quotation marks etc, they will get confusing. I modified as little code as possible to make it work. From here onwards, it's your own personal preference if you want to edit some more.

if (this > that) { ?>
<select name="numberCounter" id="numberCounter">

<?php 
for ($i=1; $i<=100; $i++)
{ ?>


<option value="<?php echo $i ?>"><?php echo $i ?></option>;

<?php }
} ?>

</select>
cmprogram
  • 1,854
  • 2
  • 13
  • 25
  • 1
    You really should explain what you actually changed, how you did it, and why. This way OP can _learn_ what they did wrong, and they can _learn_ the proper ways of doing it, instead of just copying code someone else wrote. – GrumpyCrouton Oct 24 '17 at 15:29