I'm looking at websites that use php and I seea[]=val1 instead ofb=val2. My question is why are there brackets in the url? What type of code would produce this effect?
3 Answers
Why Are the Brackets in the URL?
The brackets are in the url to indicate that val1 is to be assigned the next position in the array a. If you are confused about the blank part of the bracket, look at how php arrays work.
What Kind of Code Would Produce This?
As for the code that would create such a url, it could either be an explicit definition by the coder or some other script, or it could be somehow created by a form using the method="get" attribute.
Example:
To create this, you can define an array as the name of an input field like so:
<form method="get"> <input name="a[]" ... /> <input name="a[]" ... /> <input name="a[]" ... /> </form> Or you can just make a link (the a tag) with this url:
<a href="foo.php?a[]=val1&a[]=val2&a[]=val3">Click Me!</a>
To parse this url with PHP, you would use the $_GET variable to retrieve the values from the url:
<?php $a = $_GET['a']; $val1 = $a[0]; $val2 = $a[1]; $val3 = $a[2]; ... print_r($a); ?> The printout of the print_r($a) statement would look like this (if you wrapped it in a <pre> tag):
Array ( a => Array ( 0 => 'val1', 1 => 'val2', 2 => 'val3' ) ) Comments
That is the syntax for appending a new element to an array. There should be dollar signs preceding each variable:
$a[] = $val1; 1 Comment
You would see input fields on the page before, like:
<input name="color[]" type="checkbox" value="red"> <input name="color[]" type="checkbox" value="blue"> <input name="color[]" type="checkbox" value="green"> wherein the user could select multiple responses and they would be available in the $color array in the $_GET (and URL) of the action page, showing up like you describe.
(Similarly it could also be hidden variables passed as an array that are not based on user input.)
something.php?a[]=val1in the address?