Pass two values from a radio button when clicked

Pass two values from a radio button when clicked

You might go through a situation where you need to pass more than 1 value using radio buttons. We can pass multiple values with a radio button and can fetch them in PHP with a simple trick. In this article, we will see how to pass two values from a radio button when clicked.

We need to use a different prefix with a unique separator for example “,” or underscore “_” or colon “:”  to separate data from a string. For example, if you want to pass 2 values Mango and Fruit then we can either do it as “Mango, Fruit”, “Mango_Fruit” or “Mango:Fruit”. In this article, we have taken an example of a comma-separated option. Please note that you can use any separator of your choice, however it should be unique.

Now, let’s write some code.

The HTML

At first, we need to define the radio element, which is the HTML’s form element.

We will use a set of values comma-separated with a comma. For example, please see below:

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

<input type="radio" name="option" value="Onion, Vegetable" id="option2" /> 
<label for="option2">Onion</label> <br> 

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

<input type="radio" name="option" value="Onion, Vegetable" id="option4" /> 
<label for="option4">Onion</label> <br> 

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

<input type="radio" name="option" value="Onion, Vegetable" id="option6" />
<label for="option6">Onion</label> <br> 

Here, we have used “,” as a separator. You can structure the form as per your template.

The PHP

Now, we need to write the backend logic to get the values from the selected radio button.

The first step is to convert the value into an array. We will use explode() function.

The explode() function is used to convert a string into an array. It uses a separator which is a mandatory parameter of this function. In our case, that separator is a comma.

<?php
	// split into comma separate array
	$option = explode(",", $_POST['option']);
	
	// get value at first index
	$option_value = $option[0];

	// get value at second index
	$option_type = $option[1];
?>

and that’s 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 on a radio button. You can pass as many values as you want. These values can be fetched from the indexes of an array.

Tags:

Related Posts