Logo

Documentation

/home/vhsh1501/documentation.benjamin-bruant.com/wp-content/themes/zetheme/single.phpsingle

PHP Forms : radio button

Tableau de données fournies à l’utilisateur :

<?php
...
$cornets = [
    "Pot" => 2,    // bouton radio car choix exclusif
    "Cornet" => 3
];
...

fonction radio()dans functions.php :

function radio(string $name,string $value,array $data){
  $attributes = '';
  if (isset($data[$name]) && $value===[$name]){
    $attributes .= 'checked';
  }
  return <<<HTML
  <input type="radio" name="{$name}" value="$value" $attributes>
HTML;
}

Déploiement des éléments input type="radio"dans le formulaire:

<h2>Choisissez votre cornet</h2>

        <?php foreach ($cornets as $cornet => $prix) : ?>
            <div class="checkbox">
                <label for="">
                    <?= radio('cornet', $cornet, $_GET) ?>
                    <?= $cornet ?> - <?= $prix ?>€
                </label>
            </div>
        <?php endforeach ?>

Affichage didactique du contenu de la variable $_GETreliées à la methode homonyme :method="GET":

<h2>$_GET</h2>
<pre>
    <?php var_dump($_GET)
    ?>
</pre>
$_GET

array(1) 
{
  ["cornet"]=>
  string(3) "Pot"
}