views:

323

answers:

3

Radio box code:

<input
  type  = "radio"
  name  = "choice"
  value = "A" />Apples />

<input
  type  = "radio"
  name  = "choice"
  value = "B" />Oranges<br />

$choice=array("A"=>1.00, "B"=>0.80);
echo $choice["A"]; // will give me the value of 1.00
echo $choice["B"]; // will give me the value of 0.80

Given the code snippet above, is there anything wrong in terms of either the HTML radio box, the array or the choices?

+3  A: 

Nope, that looks perfectly fine.
Except for the random /> after your Apples text, but I suspect this is a typo?

You may also want to consider this. Probably what you are heading towards? :)

<?php
$choices = array("A"=>1.00, "B"=>0.80);
if(in_array($_REQUEST['choice'], array_keys($choices))) {
    echo $choices[$_REQUEST['choice']];
}
else {
    echo "Invalid choice received!";
}
?>

This would be the code that receives your radio choice. It makes sure the choice is valid and then prints it.

Atli
Radio button does not submit an array unless you specifiy an [] in a name, and even then I think radio button won't submit an array cause radio button is a single choice input.
dfilkovi
@dfilkovi Nobody is using the value of the radio buttons as an array... If you name multiple buttons the same you will only be able to select one of them, the value of which will be passed to PHP. If you specify the name of the buttons as an array *(by adding [])*, the value of the selected one will simply be passed as the first element of an array named after the boxes.
Atli
Amazing, enlightening, and superb, thank you, Atli
Newb
Except for the random />, caused by excessive copy and paste, thanks for pointing that out.
Newb
+1  A: 

As far as i understood your question, PHP Code seems to be wrong. You have not specified an array in your html code which is done using [ ].

This is what you do in you php code to echo the selection of the radio:

echo $_REQUEST['choice'];

This will echo selected radio buttons value either A or B.

Sarfraz
A: 

I'm not sure what are you trying to achieve, but there are several things that need your attention.

First of all, check the syntax of <input>: http://www.w3schools.com/html/html_forms.asp

So I'd change your html code to:

<form ... >
<input type="radio" name="choice" value="1.00" /> Apples
<br />
<input type="radio" name="choice" value="0.80" /> Oranges
</form>

And on server side, after actually submitting the form, just look for $_POST[ "choice" ] for your desired value (1.00 or 0.80).

Ondrej Slinták