Multiple Checkbox (PHP Array) with Examples
by Sam
A checkbox group allows user to select one or more options at the same time. Each checkbox is treated individually, so user can check the status of it either on or off. However, if we select multiple checkbox, it returns only the last item selected by the user after the form has been submitted. In this case, how can we retrieve all the items selected?
Let’s take a look at the examples below.
Example 1.
Display the courses selected by the user. Consider the image below.
<?php
if( isset($_POST['submitcourse'])){
if(isset($_POST['course'])){
echo "You selected : <br>";
foreach ($_POST['course'] as $value) {
echo $value . " <br> " ;
}
}
}
?>
<h1>Example 1: Courses</h1>
<form action="" method="POST">
<input type="checkbox" name="course[]" value="Computer Science"> Computer Science <br>
<input type="checkbox" name="course[]" value="Information Technology"> Information Technology <br>
<input type="checkbox" name="course[]" value="Computer Engineering"> Computer Engineering<br>
<input type="checkbox" name="course[]" value="Information System"> Information System<br><br>
<input type="submit" name="submitcourse" value="Submit">
</form>
Example 2. Seats
Let’s allow users to choose the seats he/she wants. After clicking submit, you should display the seats number and the total amount to be paid by the user based on the seats he/she selected. The price per seat number is $500 only.
<?php
if( isset($_POST['booknow'])){
if(isset($_POST['seat'])){
$amount = 0;
$seats = [];
foreach ($_POST['seat'] as $value) {
$amount = $amount + 500;
array_push($seats, $value);
}
echo "The total amount to be paid is: $" . $amount . "<br>";
echo "The seat is/are : " . implode(",", $seats);
}
}
?>
<form action="" method="POST">
<input type="checkbox" name="seat[]" value="1"> 1
<input type="checkbox" name="seat[]" value="2"> 2
<input type="checkbox" name="seat[]" value="3"> 3 <br><br>
<input type="checkbox" name="seat[]" value="4"> 4
<input type="checkbox" name="seat[]" value="5"> 5
<input type="checkbox" name="seat[]" value="6"> 6 <br><br>
<input type="submit" name="booknow" value="Submit">
</form>
Now, don’t get confused if this is your first time to encounter array_push($seats, $value);
. array_push() is used to insert a value into our array. If you noticed, we initialized our array as empty, $seats = []
. We inserted the $value
inside the foreach loop then we converted the array value to string using implode
and append comma for each value
Challenge
Now, it’s your time to solve our challenge below.
Create a php script that will allow the user to select seats. Then you should be able to display the seat number/s and the total amount to be paid.
Expected Ouput:
The Seats are 3,5,6 and the total amount to be paid is $700.
Don’t forget to write down your solution on the comment section below.
-
Pingback: Implode vs Explode in PHP - codespeaker