๐ŸŽ“ A1Learner
๐Ÿ”

PHP Superglobals

Superglobals are special arrays that PHP fills with values from a request. They are ready before the first line of code runs.

An empty $_GET array

No request exists on this machine, so nothing filled the array. The empty shape is the evidence.

<?php
print_r($_GET);

An empty $_POST array

No form was submitted to this program. Its array prints the same empty shape.

<?php
print_r($_POST);

Checking a key with isset

isset asks whether a key exists in an array. The answer is false here because the name key is absent.

<?php
var_dump(isset($_GET["name"]));

Example

<?php
if (isset($_GET["name"])) {
  echo "Name found\n";
} else {
  echo "No name given\n";
}

Key points

  • The query string is the part of a page address after the question mark.
  • $_GET holds the values from the query string.
  • $_POST holds the values from a submitted form.
  • Reading a key that is not there gives a warning.
  • Checking a key before reading it is the safe habit.

In this example, isset checks the name key in $_GET. The key is absent, so the else branch runs. The program prints No name given.

Note

Superglobals can be read in any part of a program.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

What does var_dump(isset($_GET["city"])) print when the city key is absent?