Roberta Gimenez
Roberta Gimenez

Reputation: 131

Array of checkbox values in PHP

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?

Upvotes: 0

Views: 110

Answers (1)

The fourth bird
The fourth bird

Reputation: 163632

$_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];
}

Upvotes: 2

Related Questions