03-Apr-2023
.
Admin
Hi Guys,
In this example,I will learn you how to get multiple values of selected checkboxes in php.you can easy and simply get multiple values of selected checkboxes in php.
our primary goal is to get values of multiple checked or selected checkboxes and implement checkboxes validation in PHP 7.
Step 1: Create Form with Multiple Checkboxes
Create a form using HTML form element, define input field with the type="checkbox" value. The checkArr[] is an array object which is defined in the name-value, which is used to communicate with the PHP.
<form action="" method="post">
<label>
Laravel
<input type="checkbox" name="checkArr[]" value="Laravel">
</label>
<label>
Java
<input type="checkbox" name="checkArr[]" value="Java">
</label>
<label>
HTML
<input type="checkbox" name="checkArr[]" value="HTML">
</label>
<label>
CSS
<input type="checkbox" name="checkArr[]" value="CSS">
</label>
<input type="submit" name="submit" value="Choose options" />
</form>
Step 2: Read Multiple Values from Selected Checkboxes
The isset($_POST[‘submit’]) method checks whether the submit value is declared or not.
In the isset function, we are employing another validation and making sure whether the checkboxes’ values are set or not using the empty() function.
Use the foreach() loop to iterate over every selected value of checkboxes and print on the user screen.
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['checkArr'])){
foreach($_POST['checkArr'] as $checked){
echo $checked."</br>";
}
}
}
?>
Step 3: Checkboxes Validation in PHP
To add the validation in checkboxes, place the following code in your PHP template.
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['checkArr'])){
foreach($_POST['checkArr'] as $checked){
echo $checked . '<br>';
}
} else {
echo '<div class="error">Checkbox is not selected!</div>';
}
}
?>
It will help you...
#PHP