kmunky
kmunky

Reputation: 15583

PHP multiple radio buttons

how can i process all radio buttons from the page?

<input type="radio" name="radio_1" value="some" />
<input type="radio" name="radio_1" value="some other" />

<input type="radio" name="radio_2" value="some" />
<input type="radio" name="radio_2" value="some other" />

this buttons will be added dynamically so i will not know the radio buttons name(and also the number of the buttons). Is there a way to get all radio values, with a for loop or something like this? thanks

Upvotes: 0

Views: 9619

Answers (3)

Oz.
Oz.

Reputation: 5458

Use a foreach loop

<?php
foreach ( $_POST as $key => $val )
    echo "$key -> $val\n";
?>

$key will be the name of the selected option and $val, well, the value.

Upvotes: 2

jheddings
jheddings

Reputation: 27553

Since the browser will just change all your input to HTTP-formatted form data, you won't be able to tell what data is from a radio button versus a text box or other input.

If the naming convention is the same as your example, just loop until you don't find a value:

<?
  for ($idx = 1; $idx <= 1000; $idx++) {
    if (isset($_REQUEST["radio_$idx"])) {
      // handle value
    }
  }
?>

EDIT Alternatively, if your form is generated dynamically, you could write the number of radio buttons it created as a hidden field in the form.

If you are able to alter the form that is being generated, you could write a hidden input that provided a list of all the radio buttons that you want to look for. As you are writing the radio buttons, just make a semi-colon-separated list of all the names that you make. When you are done, write that to a hidden input. Something like this:

On the source form:

<input type="hidden" name="radio_button_list" value="some_value;other_value" />

Then in your handler:

<?
  $list = explode(';', $_REQUEST['radio_button_list']);
  foreach ($list as $name) {
    $value = $_REQUEST[$name];
    // handle name & value
  }
?>

Upvotes: 1

Pekka
Pekka

Reputation: 449385

jheddings' example says it all. However, you will never get the names / values of all buttons - just the selected one from each group. If you need literally all values, you will have to use Javascript.

Upvotes: 0

Related Questions