1

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
  • 1
    Are you talking about QueryStrings? something.php?a[]=val1 in the address? Commented Jul 6, 2012 at 23:02
  • 1
    That's a QueryString then, it is used to easily pass data into a page without having to POST it or do any other kind of wizardry. en.wikipedia.org/wiki/Query_string Commented Jul 6, 2012 at 23:07
  • Something related to multiple-select controls ? Commented Jul 6, 2012 at 23:07

3 Answers 3

2

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' ) ) 
Sign up to request clarification or add additional context in comments.

Comments

1

That is the syntax for appending a new element to an array. There should be dollar signs preceding each variable:

$a[] = $val1; 

1 Comment

Close, but he's talking about in the URL. It's a posted array of inputs.
1

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.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.