0

I have added two checkboxes on page with submit button. After submitting there is a method having foreach loop to check which checkbox is checked , and that checkbox value should get in variable. If both checkbox's are checked then it should append both values in variable. But in my case the values are repeating. And also if i check both checkboxes it is picking up only second checkbox value.

Below is my code for HTML :

<form name="" action="" method="post">
  <input type="checkbox" name="checkbox[]" value="Training"/> Training <br/><br/>
  <input type="checkbox" name="checkbox[]" value="Posting"/> Posting<br/><br/>

  <input type="submit" value="Submit"/>
 </form>

Code for PHP:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
                     {
$value = "";
$name = $_POST['checkbox'];

// optional
// echo "You chose the following color(s): <br>";

foreach ($name as $value){
 //echo $value.", ";
 $value .= $value;

}
echo $value;
//print "<script>alert('".$value."')</script>";
}
 ?>
2
  • What do you mean with your values are repeating? Do you get the same name twice or? Commented Jul 16, 2015 at 13:01
  • yes i am getting same name twice.... for example if i check 1st checkbox having value "Training" then in output i am getting TrainingTraining, & if i check only checkbox 2 having value "Posting" thin in output i am getting PostingPosting, & if i check both checkboxes i am getting "PostingPosting," Commented Jul 17, 2015 at 4:56

2 Answers 2

2

$value is a local variable to the loop it get overwritten when the loop continues again.

$result = '';
foreach ($name as $value){
    $result .= $value;
}
echo $result;
Sign up to request clarification or add additional context in comments.

Comments

0
$name = (array)$_POST['checkbox'];
$value = '';
foreach ($name as $val){
    $value .= $val;
}

1 Comment

(array) in front of the $_POST is not necessary, name="checkbox[]" creates the array and sends it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.