xhallix
xhallix

Reputation: 3011

php form multiple radio buttons

I'm trying to find a generic way to call out which radio button has selected. Problem is, while using $_GET in my foreach loop, also submit button is echo in the loop.

Can anyone tell me how to avoid this, so that I just show up the radio buttons? I do not know a way, because foreach just accepts arrays as far as I know

here is my code

<form action="" method="get">
<input type="radio" name="one" value="One1" />One1<br/>
<input type="radio" name="one" value="One2" />One2 <br/>
<input type="radio" name="one" value="One3" />One3<br/>
<input type="submit" name="submit"/> <br/>
</form>



if(isset($_GET['submit'])){
    foreach( $_GET as $key=>$val){
        echo "$val <br/>";
    }
}

Upvotes: 2

Views: 8665

Answers (2)

Orangepill
Orangepill

Reputation: 24645

You don't need a loop just do this.

<form action="" method="get">
<input type="radio" name="one" value="One1" />One1<br/>
<input type="radio" name="one" value="One2" />One2 <br/>
<input type="radio" name="one" value="One3" />One3<br/>
<input type="submit" name="submit"/> <br/>
</form>


<?php
if(isset($_GET['one'])){
     echo "You submitted ".$_GET["one"];
}
?>

When you are trying to do something with a known key in an array there is not reason not to access it directly like this.

Upvotes: 1

liyakat
liyakat

Reputation: 11853

just try to add if condition in your loop will not show submit button in your form.

if(isset($_GET['submit'])){

    foreach( $_GET as $key=>$val){
      if($key != 'submit')
        echo "$val <br/>";
    }
}

hope it will help you

Upvotes: 6

Related Questions