0

I have a HTML form with multiple checkbox selection. They are defined as:

<label class="container">Afghanistan
        <input type="checkbox" id="Afghanistan" name="country[]" value="Afghanistan" checked="checked">
        <span class="checkmark"></span>
    </label>
    <label class="container">Armenia
        <input type="checkbox" id="Armenia" name="country[]" value="Armenia" checked="checked">
        <span class="checkmark"></span>
    </label>
...

After submitting, I call a PHP file where I want to store their values in an array.

for($i=0;$i<sizeof($_POST["country[]"]);$i++){
    $country[i] = htmlspecialchars($_POST["country[i]"]);
  }

But this code doesn't work. Can anyone help me to solve it?

2
  • Is this html wrapped in a form with method="post"? Commented Jun 5, 2018 at 16:02
  • Yes: <form id="form_id" action="localhost/food_values.php" method="post" name="myform"> It reads the checkboxvalues but I don't know how to manage the multiple options instead of only one Commented Jun 5, 2018 at 16:03

1 Answer 1

2

$_POST["country"] is an array for which you can get the values using the index using $i

Try it like this:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    for($i=0;$i<sizeof($_POST["country"]);$i++){
        $country[] = htmlspecialchars($_POST["country"][$i]);
    }
    echo $country[0];
}
Sign up to request clarification or add additional context in comments.

2 Comments

it should be $country[] = htmlspecialchars($_POST["country"][$i]); echo $country[$i];
@xam That is correct, I have updated my answer. If you want your values in an array you could add them like $country[] = htmlspecialchars($_POST["country"][$i]); and retrieve them for example like $country[0]

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.