Search code examples
phpdrop-down-menuradiobuttonlist

Using if to echo statements based on radio button AND drop down list choices PHP


I've looked all over the internet for an answer to this specific question but can't seem to find one. Basically, I've got a set of radio buttons and a drop down list that you can choose options from.

<form method="get" action="phpindex.php">
    <select name="season">
        <option value="">- Season -</option>
        <option value="spring">Spring</option>
        <option value="summer">Summer</option>
        <option value="fall">Fall</option>
        <option value="winter">Winter</option>
    </select>
    <br /><br />
    <input type="radio" name="beer" value="heavy"/>Heavy
    <br />
    <input type="radio" name="beer" value="light"/>Light
    <br />
    <input type="submit" OnClick="show_alert"/>
</form>

Based on the combination of your choices, you get a specific statement to echo upon clicking the submit button. For example, if you choose spring as the season, and a heavy beer, a statement should be echoed based upon those choices. The problem is, the echo functions aren't working and I think it's because of the combination of radio buttons and drop down list. Here is my PHP and aforementioned echo functions that aren't working.

<?php

$beer = $_GET["beer"];
$season = $_GET["season"];
$spring = $_GET["sp"];
$summer = $_GET["summer"];
$fall = $_GET["fall"];
$winter = $_GET["winter"];
$heavy = $_GET["heavy"];
$light = $_GET["light"];


if ( in_array("spring", $season) && in_array("heavy", $beer)  ) {
echo "$state Bud"; } 
if ( in_array("spring", $season) && in_array("light", $beer) ) {
echo "$state Abita"; }
if ( in_array("summer", $season) && in_array("heavy", $beer) ) {
echo "$state Yuengling"; }
if ( in_array("summer", $season) && in_array("light", $beer) ) {
echo "$state Coors"; }
if ( in_array("fall", $season) && in_array("heavy", $beer) ) {
echo "$state PBR"; }
if ( in_array("fall", $season) && in_array("light", $beer) ) {
echo "$state Miller"; }
if ( in_array("winter", $season) && in_array("heavy", $beer) ) {
echo "$state Natty"; }
if ( in_array("summer", $season) && in_array("light", $beer) ) {
echo "$state Kona"; }

$state = "Well, it looks like it's $season, and you want a $beer beer, so try this brew out:";


?>

Any help would be appreciated!


Solution

  • $_GET elements used in this way can only be simple data types, not arrays, because each segment of the query string (e.g. q=v) is defined to represent a single value v -- with key q in the $_GET array.

    As pointed out below, there is an exception to this when "array[]" is used for the name attribute of the input tag which, in this specific case, creates an array in $_GET/$_POST.

    In your case, you want to test against the values directly as strings:

    if ($season == "spring" && $beer == "heavy")

    for example.