Receiving data with $_GET
Learn to read URL parameters with $_GET.
Receiving data with $_GET
The $_GET superglobal stores the query string parameters that follow the ? in a URL as an associative array. For example, in page.php?name=Alice&age=30, $_GET['name'] is 'Alice' and $_GET['age'] is '30'.
Values are always strings; if you need numbers, cast with (int). In CLI $_GET starts empty; for testing you can fill it with parse_str().
Parsing a query string with parse_str
The parse_str($s, $output) function parses a query string into an associative array. The second argument is required in PHP 8 and receives the parsed result.
Example: after parse_str("name=Alice&age=30", $_GET);, $_GET['name'] becomes 'Alice'. In CLI scripts this makes manual testing easy without a web server.
Exercise Fill $_GET with a query string and print
Use parse_str() to fill $_GET with the query string "name=Michael&city=London". Then write echo $_GET['name'] . "\n"; and echo $_GET['city'] . "\n";.
Show example solution
Fill with parse_str("name=Michael&city=London", $_GET); then write echo $_GET['name'] . "\n"; and echo $_GET['city'] . "\n";.
Example solution:
<?php
// Fill $_GET with a query string and print
parse_str("name=Michael&city=London", $_GET);
echo $_GET['name'] . "\n";
echo $_GET['city'] . "\n";
Test yourself
-
Complete the parse_str call
parse_str("product=Pen", ____);Show answer
parse_str("product=Pen", $_GET); -
In page.php?lang=tr&page=5, what is $_GET['lang']?
- '5'
- 'tr'
- 'page'
- 'lang'
Show answer
'tr' — Correct. The value of lang is 'tr'; parameters are separated by &.
-
Match the URL parameter to its $_GET key
- ?name=Alice
- $_GET['name']
- ?page=2
- $_GET['page']
- ?lang=tr
- $_GET['lang']
- ?id=42
- $_GET['id']