PHP: ? and & in URLs - what's the difference?

php, url

Solution

The `?` marks the beginning of the query string, the `&` is used to separate individual variables within the query string.

So for instance, I'll modify your example to be a little more clear:

http://www.site.com/index.php?someVar=firstVal&otherVar=secondVal

The "location" part of the URL is everything up to but not including the `?`, so it would be simply:

http://www.site.com/index.php

This is what you're web server will use to find which script to execute. Then it will split off the query string (everything after the `?`) and pass that to your script (or more accurately, to PHP). The query string would be all of:

someVar=firstVal&otherVar=secondVal

PHP will then parse the query string, using the `&` as the delimiter between variables. So this query string would include two variables: `someVar` with value `firstVal`, and `otherVar` with value `secondVal`.

PHP will store the results of parsing the query string in the `$_GET` super global variable, which is just an associative array where the keys are the names of the parameters, and the values are of course the associated values.

So in PHP, if you do `var_dump($_GET)` with this example, it will look like this:

array(2) {
  ["someVar"]=>
  string(5) "firstVal"
  ["otherVar"]=>
  string(5) "secondVal"
}

Problem

what is the difference between ? and & in URLs? e.g. `http://www.site.com/index.php?someVar=value&otherVar=value`

Original source