phpundefined-index

Undefined index PHP with echo radio buttons value


<h1> Hotel kamer reservering </h1>
<br><br>

<form method="POST">
<input name="radio" type="radio" value="éénpersoonskamer">éénpersoonskamer</input><br><br>
<input name="radio1" type="radio" value="tweepersoonskamer">tweepersoonskamer</input><br><br>
<input name="radio2" type="radio" value="ontbijt">ontbijt</input><br><br><br>
<input name="radio3" type="radio" value="lunch">lunch</input><br><br><br>
<input name="radio4" type="radio" value="diner">diner</input><br><br><br>
<input name="submit" type="submit" <value="Klik"></input>
</form>

<?php 

if(isset($_POST['submit']) and ! empty($_POST['submit'])) {
    if(isset($_POST['radio']) ||  ($_POST['radio1']) || ($_POST['radio2']) || ($_POST['radio3']) || ($_POST['radio4']) ) {
        $radio = $_POST['radio'] . '&nbsp' . $_POST['radio1'] . '&nbsp' . $_POST['radio2'] . '&nbsp' . $_POST['radio3'] . '&nbsp' . $_POST['radio4'];
        echo $radio;
    }
}
?>

I am a beginner with PHP, am learning it now but i can't seem to lose the undefined index message. If i choose all then it won't give a bad message. Can someone explain me how i can fix this with this code and how i can resolve it with another code in the future.

I am thankfull for your time.


Solution

  • A better approach, as I guess you really are looking for a combination of radio- and checkboxes and that you want to output the checked options:

    <h1> Hotel kamer reservering </h1>
    <br><br>
    
    <form method="POST">
    <input name="roomtype" type="radio" checked="checked" value="éénpersoonskamer">éénpersoonskamer <br><br>
    <input name="roomtype" type="radio" value="tweepersoonskamer">tweepersoonskamer <br><br>
    <input name="food[]" type="checkbox" value="ontbijt">ontbijt <br><br><br>
    <input name="food[]" type="checkbox" value="lunch">lunch <br><br><br>
    <input name="food[]" type="checkbox" value="diner">diner <br><br><br>
    <input name="submit" type="submit"> 
    </form>
    
    <?php 
    
    if(!empty($_POST['submit'])) {
        echo "roomtype: " . $_POST['roomtype'] . "<br>";
        $food = $_POST['food'];
        foreach ($food AS $k => $v) {
            echo "Food $k = $v<br>";
        }
    }
    ?>