phphtmlforeachrequiredfieldvalidator

Set only a single input (type=radio ) to "required" within php foreach loop


I am stuck with the following problem:

I dynamically create Inputs of type radio within a php foreach loop. However, I want only the first input that is created to have the "required" property.

My Code is similar to this:

<?php foreach ($data as $value) 
{
?>
    <div class="radio">
        <label>
            <p>
                <input type="radio" name="option" class="option" value="<?php echo $value['id']; ?>">
                    <?php echo $value['text']; ?>
            </p>
        </label>
    </div>
<?php                                                                                               }
?>

Any way I can solve this? Any help is appreciated! Thanks


Solution

  • For example, you can do like it:

    <?php 
    $num = 0;
    foreach ($data as $value) {
    $num++;
    ?>
        <div class="radio">
            <label>
                <p>
                    <input type="radio" name="option" class="option" value="<?php echo $value['id']; ?>" <?php echo ($num == 1) ? 'required' : ''; ?>>
                        <?php echo $value['text']; ?>
                </p>
            </label>
        </div>
    <?php
    }
    ?>