HTMLPHP

Pass two values from a radio button when clicked

0
1.8k
2017 / 08 / 15

You might went through a situation where you need to pass more then 1 value using radio buttons. We can pass multiple values  with radio button and can fetch them in PHP and with a simple trick you can achieve this quite easily.

We need to use diffrent prefix with unique separator  for example “,” or underscore “_” or colon “:”  to separate data from a string. See the code below:

 

HTML Code:

<input type="radio" name="option" value="Mango, Fruit" /> <label>Mango</label> <br>

<input type="radio" name="option" value="Onion, Vegetable" /><label>Onion</label>

I have used “,” as a seperator.

 

The PHP Code:

<?php
  $option = explode(",", $_POST['option']);
  $option_value = $option[0];
  $option_type = $option[1];
?>

and thats it!

So when you select Mango, you will get “Mango” in $option_value and “Fruit” in $option_type.

You can see that we have passed 2 values in a radio button, you can pass as many values as you want. These values can be fetched from indexes of array.

 

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks