suhas
suhas

Reputation: 173

how to store all checkbox values in array in php

i m trying to store checkbox values inside variable $days but when i store this value to database it just store the last selected checkbox inside the database... please help me to sort out the code so i can get all selected values

    <?php

   if (isset($_POST['days'])) {
    foreach ($_POST['days'] as $day) {
        $days = " " . $day;
    }
} else {
    $days = "not available";
}  
?>
 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<tr>
<td>Select Days :</td>
<td>
    <input type="checkbox" name="days[]" value="Sunday">Sunday
    <input type="checkbox" name="days[]" value="Monday">Monday
    <input type="checkbox" name="days[]" value="Tuesday">Tuesday
    <input type="checkbox" name="days[]" value="Wednesday">Wednesday
    <input type="checkbox" name="days[]" value="Thursday">Thursday
    <input type="checkbox" name="days[]" value="Friday">Friday
    <input type="checkbox" name="days[]" value="Saturday">Saturday
    <input type="checkbox" name="days[]" value="All Days">All Days
</td>
<td></td>

Upvotes: 0

Views: 9046

Answers (4)

GolezTrol
GolezTrol

Reputation: 116110

You assign a normal string to $days and overwrite it on each iteration. You could append to it, by using the .= operator. ($days .= ' ' . $day), but maybe easier is to use implode:

if (isset($_POST['days'])) {
  $days = implode(' ', $_POST['days']);
} else {
  $days = "not available";
}  

Note there is a small functional difference. implode will add spaces inbetween the days, while the foreach loop will also put a space at the start.

Upvotes: 3

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Use . to concatate the string

$days .= " " . $day;

Upvotes: 0

Siim Kallari
Siim Kallari

Reputation: 861

You need to make $days as array and then push the values you get from checkbox into array.

$days[] = $day

inside your foreach statement

Upvotes: -1

arkascha
arkascha

Reputation: 42915

You overwrite $days with each iteration of the forech loop. Instead you want to add to it. Most likely this is what you are looking for:

if (isset($_POST['days'])) {
    foreach ($_POST['days'] as $day) {
        $days .= " " . $day;
    }
} else {
    $days = "not available";
}  

If so, then you can even simplify the code and remove the loop:

if (isset($_POST['days'])) {
    $days = implode(" ", $_POST['days']);
} else {
    $days = "not available";
}  

Upvotes: 0

Related Questions