Reputation: 1115
I have a form where I added a group of check boxes like below:
<form action="next.php" method="get">
<input name="c1" value="1" type="checkbox">
<input name="c1" value="2" type="checkbox">
<input name="c1" value="3" type="checkbox">
<input name="c1" value="4" type="checkbox">
...
</form>
If I select the first and the 3rd check box, the URL looks good when I press the submit button, like
?c1=1&c1=3 [...]
but the $_GET array holds only the last value of c1. I know I could use the []
notation to get an array, but then the link looks like
?c1[]=1&c1[]=3 [...]
I saw sites that generate the URL without the []
and still manage to take all values into account. How do they do that ?
Thank you !
Upvotes: 2
Views: 321
Reputation: 905
You can still access the entire querystring. You can parse the querystring into parts like so:
$qs = explode("&",$_SERVER['QUERY_STRING']);
foreach ($qs as $part) {
if (strpos($part,"c1") !== false) {
$split = strpos($part,"=");
$values[] = substr($part, $split + 1);
}
}
var_dump($values);
If your querystring looks like this: ?c1=1&c1=3 the code above leaves you with a result like this:
array(2) {
[0]=> string(1) "1"
[1]=> string(1) "3"
}
Upvotes: 0
Reputation: 1826
Use have to use this:
<input name="c1[]" value="1" type="checkbox">
<input name="c1[]" value="2" type="checkbox">
<input name="c1[]" value="3" type="checkbox">
<input name="c1[]" value="4" type="checkbox">
Upvotes: 0
Reputation: 360792
PHP requires you to use a pseudo-array notation if you want to use the same fieldname for multiple different form elements:
<input type="checkbox" name="c1[]" ... />
<input type="checkbox" name="c1[]" ... />
<input type="checkbox" name="c1[]" ... />
etc...
The []
tells PHP to treat c1
as an array, and keep all of the submitted values. Without []
, PHP will simply overwrite each previous c1 value with the new one, until the form's done processing.
Sites which don't use the []
notation do the form processing themselves, retrieving the query string from $_SERVER['QUERY_STRING']
and then parse it themselves.
Upvotes: 2