Core PHP 6 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Define constants with define() and const.
  • Create variables, follow the naming rules and understand loose typing.
  • Use PHP's data types and inspect them with var_dump() and gettype().
  • Explain local, global and static variable scope.
  • Know the superglobal arrays $_GET, $_POST, $_SESSION, $_COOKIE, $_REQUEST, $_SERVER, $_FILES and $_ENV.
Constants

A constant is a name (placeholder) for a value that does not change while the script runs. Constants are usually written in CAPITAL letters so that they are easy to find in the code. A constant name must begin with a letter or an underscore – never with a number – and constant names are case-sensitive. Constants are not prefixed with $.

You define a constant with the function define(). Once defined, a constant cannot be changed or undefined.

Syntax
define("CONSTANT_NAME", value);
const CONSTANT_NAME = value;      // compile-time alternative (also used in classes)
File: htdocs/phpbook/ch04/constant.php
<?php
define("SUBJECT", "PHP/MySQLi");
const INSTITUTE = "Bhopal";
echo "We all are learning: " . SUBJECT . "<br>";
echo "Batch at " . INSTITUTE . "<br>";
echo "Is SUBJECT defined? " . (defined("SUBJECT") ? "Yes" : "No") . "<br>";
echo "PHP_VERSION is a built-in constant: " . PHP_VERSION . "<br>";
echo "PHP_INT_MAX = " . PHP_INT_MAX;
?>
OUTPUT browser · http://localhost/phpbook/ch04/constant.php
We all are learning: PHP/MySQLi
Batch at Bhopal
Is SUBJECT defined? Yes
PHP_VERSION is a built-in constant: 8.3.6
PHP_INT_MAX = 9223372036854775807

Trying to define the same constant again produces a warning "Constant SUBJECT already defined", and the old value is kept. In PHP 8 the third argument of define() (case-insensitive constants) is no longer supported.

Variables

Variables store values – text strings, numbers or arrays. Once a variable is declared it can be used again and again in the script. All variables in PHP start with a $ sign.

Syntax
$var_name = value;

New PHP programmers often forget the $ sign at the beginning of the variable – then it does not work. Let us create a variable containing a string and a variable containing a number:

File: htdocs/phpbook/ch04/variables.php
<?php
$txt = "Hello World!";
$x = 16;
$price = 99.50;
echo $txt . "<br>";
echo "x = $x and price = $price<br>";
$x = $x + 4;            // a variable can be changed
echo "Now x = $x";
?>
OUTPUT browser · http://localhost/phpbook/ch04/variables.php
Hello World!
x = 16 and price = 99.5
Now x = 20
PHP is a loosely typed language

In PHP a variable does not need to be declared before a value is assigned to it, and you do not tell PHP which data type it has. PHP automatically gives the variable the correct data type, depending on its value. In a strongly typed language (C, Java) you must declare the type and the name of a variable before using it.

Naming rules for variables
  • A variable name must start with a letter or an underscore _ (after the $).
  • A variable name may contain only letters, numbers and underscores (a–z, A–Z, 0–9, _).
  • A variable name must not contain spaces. Write multi-word names as $my_string or $myString.
  • Variable names are case-sensitive: $Employee and $employee are different variables.
Data Types
TypeHoldsExample
int (integer)Whole numbers$age = 25;
float (double)Real numbers with a decimal point$pi = 3.14;
stringA sequence of characters (text)$name = "Asha";
bool (boolean)true or false$paid = true;
arrayA set of values under one name$a = [1, 2, 3];
objectAn instance of a class$d = new DateTime();
null"No value"$x = null;
resourceA handle to an external resource$f = fopen("a.txt","r");

var_dump() shows the type and the value of a variable; gettype() returns the type name as a string.

File: htdocs/phpbook/ch04/datatypes.php
<?php
$i = 42;
$f = 3.75;
$s = "PHP";
$b = true;
$a = array("red", "green");
$n = null;
echo "<pre>";
var_dump($i);
var_dump($f);
var_dump($s);
var_dump($b);
var_dump($a);
var_dump($n);
echo "gettype(\$f) = " . gettype($f) . "\n";
echo "</pre>";
?>
OUTPUT browser · http://localhost/phpbook/ch04/datatypes.php
int(42)
float(3.75)
string(3) "PHP"
bool(true)
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
}
NULL
gettype($f) = double
Type juggling and casting

Because PHP is loosely typed, it converts values automatically when needed ("type juggling"). You can also convert explicitly with a cast – (int), (float), (string), (bool), (array).

File: htdocs/phpbook/ch04/juggling.php
<?php
$a = "10";            // a string
$b = 5;               // an integer
$c = $a + $b;         // string "10" is converted to a number
echo "\"10\" + 5 = $c (type " . gettype($c) . ")<br>";
echo "\"10\" . 5 = " . ($a . $b) . "<br>";   // . joins strings
echo "(int) 12.9 = " . (int) 12.9 . "<br>";
echo "(float) \"3.5kg\" = " . (float) "3.5kg" . "<br>";
echo "(bool) 0 is ";
var_dump((bool) 0);
echo "<br>(bool) \"hello\" is ";
var_dump((bool) "hello");
?>
OUTPUT browser · http://localhost/phpbook/ch04/juggling.php
"10" + 5 = 15 (type integer)
"10" . 5 = 105
(int) 12.9 = 12
(float) "3.5kg" = 3.5
(bool) 0 is bool(false)
(bool) "hello" is bool(true)
Variable Scope

The scope of a variable is the part of the script in which it can be used. In most cases variables are local: a variable declared inside a function cannot be accessed outside the function, and a variable declared outside a function cannot be accessed inside it. To use a global variable inside a function you must declare it global or access it through the $GLOBALS array.

File: htdocs/phpbook/ch04/scope.php
<?php
$site = "phpbook";          // global scope

function showLocal() {
    $msg = "inside";        // local scope
    echo "Local msg: $msg<br>";
    echo "Global site without 'global': " . @$site . "(empty)<br>";
}

function showGlobal() {
    global $site;           // bring the global variable into the function
    echo "With global keyword: $site<br>";
    echo "With \$GLOBALS array: " . $GLOBALS['site'] . "<br>";
}

function counter() {
    static $count = 0;      // keeps its value between calls
    $count++;
    echo "counter() called $count time(s)<br>";
}

showLocal();
showGlobal();
counter(); counter(); counter();
?>
OUTPUT browser · http://localhost/phpbook/ch04/scope.php
Local msg: inside
Global site without 'global': (empty)
With global keyword: phpbook
With $GLOBALS array: phpbook
counter() called 1 time(s)
counter() called 2 time(s)
counter() called 3 time(s)
  • A static variable inside a function keeps its value between calls, instead of being reset each time.
  • The @ operator used above suppresses the warning for the undefined local $site; normally you should not hide errors this way.
register_globals (historical)

Older PHP books mention the php.ini setting register_globals. When it was on, every form field, cookie and URL parameter automatically became a normal variable – ?name=Asha created $name. This allowed attackers to inject values into variables, so the default was switched to off in PHP 4.2, it was deprecated in 5.3 and removed in PHP 5.4. Modern PHP never creates variables from request data automatically; you always read them from the superglobal arrays below.

Superglobals – Variables Passed Between Pages

Superglobals are built-in arrays that are available in every scope – inside and outside functions – without the global keyword.

SuperglobalContains
$_GET['name']Values sent in the URL / by a form with method="get".
$_POST['name']Values sent by a form with method="post".
$_REQUEST['name']Contents of $_GET, $_POST and $_COOKIE together – use when it does not matter how the value was sent.
$_SESSION['name']Values stored in the current session (Chapter 31).
$_COOKIE['name']Values of cookies sent by the browser (Chapter 30).
$_SERVER['name']Information from the web server – headers, paths, script location.
$_FILES['name']Information about uploaded files (Chapter 14).
$_ENV['name']Variables from the operating-system environment.
$GLOBALS['name']All variables of the global scope.
File: htdocs/phpbook/ch04/server.php
<?php
echo "Script name : " . $_SERVER['PHP_SELF'] . "<br>";
echo "Request method : " . $_SERVER['REQUEST_METHOD'] . "<br>";
echo "Query string : " . $_SERVER['QUERY_STRING'] . "<br>";
echo "City from \$_GET : " . $_GET['city'] . "<br>";
echo "PIN from \$_REQUEST : " . $_REQUEST['pin'] . "<br>";
echo "Server name : " . $_SERVER['SERVER_NAME'];
?>
OUTPUT browser · http://localhost/phpbook/ch04/server.php?city=Bhopal&pin=462011
Script name : /phpbook/ch04/server.php
Request method : GET
Query string : city=Bhopal&pin=462011
City from $_GET : Bhopal
PIN from $_REQUEST : 462011
Server name : localhost
Key Takeaways
  • Constants are defined with define() or const, have no $ and cannot be changed.
  • Variables start with $, need no declaration and get their type from the assigned value.
  • Variable names start with a letter or underscore and are case-sensitive.
  • PHP types: int, float, string, bool, array, object, null and resource; use var_dump() to inspect them.
  • Variables are local to functions; use global, $GLOBALS or static when needed.
  • register_globals was removed in PHP 5.4; read request data from $_GET, $_POST, $_REQUEST and the other superglobals.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch04 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : A constant is a named value that cannot change during script execution. It is defined with define("NAME", value) or with const NAME = value; and used without a $ sign.

Answer : A constant name must start with a letter or underscore, may contain letters, digits and underscores, and is case-sensitive. By convention constants are written in capital letters.

Answer : A variable is a named storage location for a value such as a string, number or array. Every variable name starts with the $ sign, e.g. $total = 100;

Answer : Because a variable does not need to be declared with a type; PHP decides the type from the assigned value and can convert it automatically when needed.

Answer : The name must start with a letter or underscore after $, may contain only letters, digits and underscores, must not contain spaces, and is case-sensitive.

Answer : int (integer), float (double), string and bool (boolean).

Answer : echo only prints the value; var_dump() prints the data type, the length (for strings/arrays) and the value, which is useful for debugging.

Answer : The automatic conversion of a value from one type to another depending on context, e.g. "10" + 5 gives the integer 15 because the + operator needs numbers.

Answer : With a cast: (int) $value, or with the function intval($value). For example (int) 12.9 gives 12.

Answer : A variable created inside a function is local and exists only in that function. A variable created outside functions is global and is not visible inside functions unless brought in with the global keyword or accessed via $GLOBALS.

Answer : A variable declared with the static keyword inside a function keeps its value between calls of that function instead of being re-initialised each time.

Answer : A php.ini setting that turned request data (form fields, URL parameters, cookies) into ordinary variables automatically. Attackers could inject values into program variables, so it was disabled by default from PHP 4.2 and removed in PHP 5.4.

Answer : Built-in associative arrays that are available in every scope, such as $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_ENV and $GLOBALS.

Answer : $_GET holds values sent in the URL query string (form method="get"); $_POST holds values sent in the body of an HTTP POST request (form method="post").

Answer : $_SERVER – for example $_SERVER['PHP_SELF'] gives the script path and $_SERVER['REQUEST_METHOD'] gives GET or POST.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which is a valid variable name?

Show Answer

Correct Answer : C. $_first_name
A variable starts with $ followed by a letter or underscore; hyphens are not allowed.

Q2. A constant created with define() is used:

Show Answer

Correct Answer : B. Without a $ prefix
Constants are referenced by name only, e.g. SUBJECT.

Q3. What does "10" + 5 evaluate to?

Show Answer

Correct Answer : B. 15
The + operator converts the numeric string to a number (type juggling).

Q4. A variable that keeps its value between function calls is declared with:

Show Answer

Correct Answer : B. static
static variables are initialised once and retain their value.

Q5. In which PHP version was register_globals removed?

Show Answer

Correct Answer : C. 5.4
It was turned off by default in 4.2, deprecated in 5.3 and removed in 5.4.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – Constants. https://www.php.net/manual/en/language.constants.php
  2. The PHP Group. (n.d.). PHP Manual – Variables. https://www.php.net/manual/en/language.variables.php
  3. The PHP Group. (n.d.). PHP Manual – Types. https://www.php.net/manual/en/language.types.php
  4. The PHP Group. (n.d.). PHP Manual – Variable scope. https://www.php.net/manual/en/language.variables.scope.php
  5. The PHP Group. (n.d.). PHP Manual – Superglobals. https://www.php.net/manual/en/language.variables.superglobals.php