Topic 2: PHP Variables (Introduction)
📖 6 min read · 🎯 beginner · 🧭 Prerequisites: insert-select-update-delete-queries, javascript-basics
Why this matters
Here's the thing — every PHP program you write will need to remember stuff. A user's name, their age, a price, a message to display on screen. Without a way to store that information temporarily, your code can't do much. In PHP, we use variables for this, and they all start with a $ sign — PHP's way of saying "this is a container holding a value." Once you understand how to create and use variables, you unlock the ability to write PHP that actually does something real.
What You'll Learn
- How to declare and name PHP variables using the
$syntax - The five core PHP data types: integers, floats, strings, booleans, and arrays
- How to use variables in arithmetic operations, string concatenation, and function calls
- The difference between global scope, local scope, and superglobal scope
- How to read form input using PHP's built-in superglobal variables
$_GET,$_POST, and$_SERVER
The Analogy
Think of PHP variables as labeled storage bins in a warehouse. Each bin has a name written on the outside — that name is the variable name — and whatever you place inside is the value. You can swap the contents of a bin at any time, and any worker on the warehouse floor (any line of your script) can grab a bin by its label and use what's inside. Some bins live on the main floor and anyone can reach them (global variables); others are locked inside a foreman's office and only that foreman can touch them (local variables); and a handful of special bins are mounted on the ceiling, visible from every corner of the warehouse no matter what (superglobals).
Chapter 1: What Are Variables?
A variable is a named container that holds data which can be used and manipulated throughout a program. In PHP, variables are essential for storing numbers, strings, arrays, and more.
Declaring Variables
Variables in PHP are declared using the $ symbol followed by the variable name. Rules for naming:
- Must start with a letter or an underscore (
_) - Can contain letters, numbers, and underscores after the first character
- Are case-sensitive —
$nameand$Nameare two different variables
<?php
$variableName = "value";
?>
Example Variables
<?php
// Integer variable
$age = 25;
// String variable
$name = "Alice";
// Float variable
$price = 19.99;
// Boolean variable
$isMember = true;
?>
Chapter 2: Variable Types
PHP supports five core data types:
- Integers — Whole numbers (e.g.,
1,2,3) - Floats — Numbers with decimal points (e.g.,
1.23,4.56) - Strings — Sequences of characters (e.g.,
"Hello, World!") - Booleans —
trueorfalsevalues - Arrays — Ordered collections of values
Example of All Five Data Types
<?php
// Integer
$age = 30;
// Float
$height = 5.9;
// String
$name = "John Doe";
// Boolean
$isStudent = false;
// Array
$colors = array("red", "green", "blue");
?>
PHP is a loosely typed language — you never have to declare the type explicitly. PHP infers it from the value you assign.
Chapter 3: Working with Variables
Variables become useful the moment you combine them: in calculations, in text assembly, and as arguments to functions.
Arithmetic Operations
<?php
$number1 = 10;
$number2 = 5;
$sum = $number1 + $number2; // Addition
$difference = $number1 - $number2; // Subtraction
$product = $number1 * $number2; // Multiplication
$quotient = $number1 / $number2; // Division
echo "Sum: " . $sum . "<br>";
echo "Difference: " . $difference . "<br>";
echo "Product: " . $product . "<br>";
echo "Quotient: " . $quotient . "<br>";
?>
String Concatenation
PHP uses the dot operator (.) to join strings — not the + operator like JavaScript.
<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName; // Concatenation using the dot operator
echo "Full Name: " . $fullName;
?>
Using Variables in Functions
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
$personName = "Alice";
echo greet($personName);
?>
Chapter 4: Variable Scope
Where you declare a variable determines where you can use it. PHP has three scope levels:
- Global Scope — Variables declared outside any function. Accessible throughout the script, but not automatically inside functions.
- Local Scope — Variables declared inside a function. Only accessible within that function; they disappear when the function returns.
- Superglobal Scope — Built-in PHP variables accessible from any scope, inside or outside functions (e.g.,
$_POST,$_GET).
Example of Variable Scope
<?php
$globalVar = "I am a global variable";
function testScope() {
$localVar = "I am a local variable";
echo $localVar; // Accessible here
}
testScope();
echo $globalVar; // Accessible here
// echo $localVar; // ERROR — $localVar is not accessible outside testScope()
?>
If you genuinely need a global variable inside a function, PHP provides the
globalkeyword — but leaning on it too often is a design smell. Prefer passing values as function arguments instead.
Chapter 5: Superglobal Variables
PHP ships with a set of built-in superglobal arrays that are automatically available in every scope of every script. The three you'll use most often:
$_GET— Collects data sent via URL query parameters (e.g.,?name=Alice)$_POST— Collects data submitted via an HTML form using the HTTP POST method$_SERVER— Contains server and execution environment information: headers, file paths, the request method, and more
Example: Reading a Form Submission with Superglobals
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Superglobal Example</title>
</head>
<body>
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, " . $name . "!";
}
?>
</body>
</html>
How it works step by step:
- The HTML form submits via POST to the same page (
action=""). - PHP checks
$_SERVER["REQUEST_METHOD"]to confirm a POST submission occurred. - It reads the submitted
namefield from$_POST['name']. - It echoes a greeting back to the user.
🧪 Try It Yourself
Task: Create a PHP script that acts as a simple tip calculator.
- Declare two variables:
$billTotal(a float, e.g.,48.50) and$tipPercent(an integer, e.g.,18). - Calculate the tip amount and the grand total.
- Echo both values to the browser with labels.
Success criterion: You should see two lines in the browser — something like:
Tip amount: $8.73
Grand total: $57.23
Starter snippet:
<?php
$billTotal = 48.50;
$tipPercent = 18;
$tipAmount = $billTotal * ($tipPercent / 100);
$grandTotal = $billTotal + $tipAmount;
echo "Tip amount: $" . number_format($tipAmount, 2) . "<br>";
echo "Grand total: $" . number_format($grandTotal, 2);
?>
Try changing $billTotal and $tipPercent to different values and reload to verify the math updates correctly.
🔍 Checkpoint Quiz
Q1. Which of the following is a valid PHP variable name?
A) $1stName
B) $_firstName
C) $first-name
D) $first name
Q2. What will the following code print?
<?php
$x = 10;
$y = 3;
echo $x . $y;
?>
A) 13
B) 103
C) 30
D) A runtime error
Q3. Given this code, what happens when testScope() is called and then echo $localVar runs outside it?
<?php
function testScope() {
$localVar = "only here";
}
testScope();
echo $localVar;
?>
A) It prints "only here"
B) It prints nothing (empty string)
C) PHP throws an undefined variable notice / warning
D) It prints null
Q4. A user submits a login form via HTTP POST. Which superglobal and key would you use to read their submitted username field?
A) $_GET['username']
B) $_POST['username']
C) $_SERVER['username']
D) $_REQUEST_BODY['username']
A1. B — $_firstName is valid. Variable names must start with a letter or underscore; $1stName starts with a digit, $first-name contains a hyphen (not allowed), and $first name contains a space.
A2. B — The dot operator concatenates strings, so 10 and 3 are joined as strings, producing "103", not the arithmetic sum 13.
A3. C — $localVar is in local scope inside testScope(). Outside the function it is undefined, so PHP emits an undefined variable notice (and outputs nothing for that variable).
A4. B — Form data submitted via the method="post" attribute is available in $_POST. $_GET is for URL query parameters; $_SERVER holds server/environment metadata; there is no $_REQUEST_BODY superglobal in PHP.
🪞 Recap
- PHP variables are declared with a
$prefix, are case-sensitive, and must start with a letter or underscore. - PHP's five core data types are integers, floats, strings, booleans, and arrays — the type is inferred automatically.
- The dot operator (
.) concatenates strings; arithmetic operators (+,-,*,/) work on numbers. - Variable scope is either global (outside functions), local (inside functions), or superglobal (everywhere).
$_GET,$_POST, and$_SERVERare superglobals used to read URL parameters, form submissions, and server information respectively.
📚 Further Reading
- PHP Variables — php.net — the source of truth on variable syntax and rules
- PHP Data Types — php.net — complete reference for all PHP types including null, objects, and resources
- PHP Superglobals — php.net — full list of built-in superglobal arrays
- ⬅️ Previous: JavaScript Basics
- ➡️ Next: Tables, Row Span, Col Span & Misc Tags