Andrew
Andrew

Reputation: 23

PHP radio button group variables

I've simplified it for this question. But all I need to do is show a different result if a combination of buttons is checked. At the moment if Rice and Tea are checked there are no results.

<?PHP

if (isset($_POST['Submit1'])) {

    $selected_radio = $_POST['food']."|".$_POST['drink'];

        if ($selected_radio == 'rice' && 'tea') {
            print '<h1>Rice and tea</h1>';

        }
        else if ($selected_radio == 'beans' && 'coffee') {
            print '<h1>Beans and coffee</h1>';
        }
}

?>  


<form name ="form1" method ="POST" action =" ">

<p><input type = 'Radio' Name ='food'  value= 'rice'>Rice</p>

<p><input type = 'Radio' Name ='food'  value= 'beans'>Beans</p>


<p><input type = 'Radio' Name ='drink'  value= 'tea'>Tea</p>

<p><input type = 'Radio' Name ='drink'  value= 'coffee'>Coffee</p>


<input type = "Submit" Name = "Submit1"  value = "Select">
</form>

(Apologies for asking a similar question earlier)

Upvotes: 1

Views: 263

Answers (3)

B001ᛦ
B001ᛦ

Reputation: 2061

Use this code:

$selected_radio_list = [
    'rice|tea' => 'foo',
    'beans|coffee' =>'bar'
];  

$post = $_POST['food']. "|" .$_POST['drink'];  

if(in_array($post, $selected_radio_list )){
    echo $selected_radio_list[$post];
}

Upvotes: 0

Change the condition of your if:

    if (strpos($selected_radio, 'rice') !== FALSE && strpos($selected_radio, 'tea') !== FALSE) {
        print '<h1>Rice and tea</h1>';

    }
    else if (strpos($selected_radio, 'beans') !== FALSE && strpos($selected_radio, 'coffee') !== FALSE) {
        print '<h1>Beans and coffee</h1>';
    }

(It's just a suggestion and I don't tested it ;))

Upvotes: 1

Bhavya Shaktawat
Bhavya Shaktawat

Reputation: 2512

Update if condition

if (isset($_POST['Submit1'])) {

    $selected_radio = $_POST['food']."|".$_POST['drink'];

        if ($selected_radio == 'rice|tea') {
            print '<h1>Rice and tea</h1>';

        }
        else if ($selected_radio == 'beans|coffee') {
            print '<h1>Beans and coffee</h1>';
        }
}

Upvotes: 2

Related Questions