Skip to main content

🐘 PHP Syntax and Variables

PHP powers a huge slice of the web — from WordPress blogs to Laravel APIs. Before you can build anything with it, you need to speak its basic grammar: how code is delimited, how variables hold values, and how PHP's easy-going type system behaves. This lesson gives you that foundation with modern, correct examples.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Write valid PHP using opening/closing tags, statements, and comments
  • Declare and use variables and understand PHP's dynamic type system
  • Work with the core data types: strings, integers, floats, booleans, arrays, and null
  • Interpolate variables into strings and choose the right quote style
  • Define constants and apply PHP's common operators correctly

Estimated Time: 30–40 minutes  •  Difficulty: Beginner

Hands-on: Build a small "receipt calculator" script that combines variables, types, and operators.

In This Lesson

What Is PHP?

PHP (a recursive acronym for "PHP: Hypertext Preprocessor") is a server-side scripting language designed for the web. When a browser requests a .php page, the server runs the PHP code, and only the resulting HTML travels to the browser — the source is never exposed.

💡 Analogy: Think of PHP as a chef working behind a kitchen door. The diner (browser) only ever sees the finished plate (HTML). Whatever recipes, measurements, and steps happened in the kitchen (your PHP logic) stay private.

This lesson targets modern PHP (8.0+). The language has evolved dramatically — today it has typed properties, named arguments, match expressions, and strong performance. We'll flag anything version-specific as we go.

📖 Key Terms

Interpreter: the program that reads and executes your PHP source line by line.

Server-side: code that runs on the web server, not in the visitor's browser.

Dynamically typed: variables don't declare a fixed type; the type is determined by the value they currently hold.

Basic Syntax: Tags, Statements, Comments

PHP code lives inside PHP tags. Everything between <?php and ?> is executed; everything outside is passed straight through as plain output (usually HTML).

<?php
echo "Hello from PHP!";
?>

In a file that is pure PHP (no trailing HTML), the convention is to omit the closing ?>. This avoids accidental whitespace being sent to the browser, which can break headers and cookies.

<?php
// A pure-PHP file: note there is no closing tag.
$greeting = "Hello, world";
echo $greeting;

Statements and the semicolon

Every PHP statement ends with a semicolon (;). Forgetting it is the single most common beginner error and produces a "syntax error, unexpected..." message.

<?php
$a = 5;
$b = 10;
echo $a + $b;   // 15

Comments

Comments document your intent and are ignored by the interpreter. PHP supports three styles:

<?php
// Single-line comment (C++ style)

# Single-line comment (shell style)

/*
   Multi-line comment.
   Handy for longer explanations
   or temporarily disabling a block.
*/

⚠️ Case sensitivity gotcha

Variable names in PHP are case-sensitive ($name and $Name are different). But function and keyword names are case-insensitive (echo, ECHO, and Echo all work). Stick to lowercase keywords for readability.

Variables

A variable is a named container for a value. In PHP, every variable name begins with a dollar sign ($), followed by a letter or underscore, then any mix of letters, numbers, and underscores.

<?php
$username   = "alice";     // string
$age        = 30;          // integer
$price      = 19.99;       // float
$isActive   = true;        // boolean
$_internal  = "ok";        // leading underscore is allowed
// $2fast    = "no";       // INVALID — cannot start with a digit

You don't declare a type. Assigning a value both creates the variable and gives it a type. Reassigning a different kind of value simply changes the type — this is what "dynamically typed" means.

<?php
$data = "hello";   // $data is now a string
$data = 42;        // the SAME variable is now an integer
$data = [1, 2, 3]; // ...and now it's an array
A variable as a labelled box A variable named dollar-price is a box; assigning the value nineteen point nine nine places that value inside the box, which can later be replaced. $price 19.99 (float) reassign $price "on sale" (string)
Figure 1 — A variable is a labelled box. Its type follows whatever value you place inside, and can change on reassignment.

Naming conventions

PHP itself doesn't enforce a style, but the community standard (PSR) uses camelCase for variables: $firstName, $totalPrice, $isLoggedIn. Choose descriptive names — $userEmail beats $e every time.

Data Types

PHP has a handful of core "scalar" types plus a few compound ones. Here are the ones you'll use daily:

TypeExampleNotes
string"hello"Text, in single or double quotes
int42Whole numbers, positive or negative
float3.14Numbers with a decimal point
booltrue / falseThe two logical values
array[1, 2, 3]An ordered map of keys to values
nullnullThe absence of a value

You can inspect a variable's type at runtime with gettype(), or dump its full value and type with var_dump() — an indispensable debugging tool.

<?php
$count = 7;
var_dump($count);        // int(7)
var_dump("7");           // string(1) "7"
var_dump(7 == "7");      // bool(true)  — loose comparison
var_dump(7 === "7");     // bool(false) — strict: type must match too

⚠️ == vs ===

The loose equality operator == converts types before comparing, which causes surprising results. Prefer the strict operator ===, which requires both the value and the type to match. This alone prevents a whole class of bugs.

Type juggling

PHP will automatically convert ("juggle") types in many contexts. For example, using a numeric string in arithmetic converts it to a number:

<?php
$result = "10 apples" + 5;   // 15 in old PHP; a TypeError-ish warning in PHP 8
$clean  = (int) "10";        // explicit cast → int(10)
$asFloat = (float) "3.5kg";  // 3.5

Explicit casts — (int), (float), (string), (bool), (array) — make your intent clear and are far safer than relying on automatic juggling.

Strings & Interpolation

Strings are everywhere in web work — HTML, messages, SQL, JSON. PHP gives you two quote styles that behave differently.

Single vs double quotes

Double quotes parse variables and escape sequences. Single quotes are literal — they treat everything as-is (except \' and \\).

<?php
$name = "Alice";

echo "Hello, $name!\n";   // Hello, Alice! (with a newline)
echo 'Hello, $name!\n';   // Hello, $name!\n  (literal — no parsing)

For clarity when a variable sits next to other characters, wrap it in curly braces:

<?php
$item = "book";
echo "I bought two {$item}s.";   // I bought two books.

Concatenation

The dot (.) operator joins strings together:

<?php
$first = "Ada";
$last  = "Lovelace";
$full  = $first . " " . $last;   // "Ada Lovelace"

$full .= "!";                     // append — now "Ada Lovelace!"

Useful string functions

FunctionPurposeExample → Result
strlen()Length in bytesstrlen("cat") → 3
strtoupper()Uppercasestrtoupper("hi") → "HI"
trim()Remove surrounding whitespacetrim(" hi ") → "hi"
str_replace()Substitute textstr_replace("a","o","cat") → "cot"
str_contains()Substring check (PHP 8)str_contains("hello","ell") → true

Constants

A constant is a value that never changes once defined. Unlike variables, constants have no $ and are conventionally written in UPPER_SNAKE_CASE.

<?php
// Modern, preferred form:
const TAX_RATE = 0.08;
const SITE_NAME = "Ray's Shop";

// Older function form (still valid, needed for dynamic names):
define("MAX_UPLOAD_MB", 25);

echo SITE_NAME;              // Ray's Shop
echo 100 * TAX_RATE;        // 8

💡 When to use a constant

Reach for a constant whenever a value is fixed for the life of the program and appears in more than one place — a tax rate, an API base URL, a maximum retry count. Naming it once prevents "magic numbers" scattered through your code.

PHP also ships magic constants that reflect where they're used: __LINE__, __FILE__, __FUNCTION__, and __DIR__ are common in logging and file includes.

Operators

Operators combine or compare values. Here are the families you'll use constantly.

Arithmetic & assignment

<?php
$sum   = 8 + 3;    // 11
$diff  = 8 - 3;    // 5
$prod  = 8 * 3;    // 24
$quot  = 8 / 3;    // 2.6666...
$rem   = 8 % 3;    // 2   (modulo — the remainder)
$pow   = 2 ** 10;  // 1024 (exponent)

$total = 100;
$total += 20;      // shorthand for $total = $total + 20  → 120
$total -= 5;       // 115

Comparison & logical

OperatorMeaning
=== / !==Strict equal / not equal (type + value)
< > <= >=Less/greater than (or equal)
&& / andLogical AND — both must be true
|| / orLogical OR — at least one true
!Logical NOT — flips a boolean
<=>Spaceship — returns -1, 0, or 1 (great for sorting)

Handy null-related operators

<?php
// Null coalescing: use the right side if the left is null/unset
$username = $_GET['user'] ?? 'Guest';

// Null coalescing assignment (PHP 7.4+)
$config['timeout'] ??= 30;   // set only if not already set

// Ternary: a compact if/else expression
$label = $isActive ? 'Active' : 'Inactive';

✅ Everyday habit

The null coalescing operator (??) is the idiomatic way to read possibly-missing values from $_GET, $_POST, arrays, and config. It replaces the clunky isset() ? ... : ... pattern you'll see in older code.

Hands-on Exercise

🏋️ Build a Receipt Calculator

Objective: Combine variables, types, string interpolation, and operators into one small script.

Instructions:

  1. Define a constant TAX_RATE of 0.08.
  2. Create variables for an item name, its unit price, and a quantity.
  3. Compute the subtotal, the tax, and the grand total.
  4. Print a tidy receipt using double-quoted interpolation and number_format() for currency.
💡 Hint

Multiply $price * $qty for the subtotal, then $subtotal * TAX_RATE for the tax. Wrap money values in number_format($value, 2) to always show two decimal places. Use {$var} braces inside strings for clarity.

✅ Example solution
<?php
const TAX_RATE = 0.08;

$item  = "Mechanical Keyboard";
$price = 79.50;
$qty   = 2;

$subtotal = $price * $qty;
$tax      = $subtotal * TAX_RATE;
$total    = $subtotal + $tax;

echo "Receipt\n";
echo "-------\n";
echo "{$qty} x {$item} @ \${$price}\n";
echo "Subtotal: \$" . number_format($subtotal, 2) . "\n";
echo "Tax (8%): \$" . number_format($tax, 2) . "\n";
echo "TOTAL:    \$" . number_format($total, 2) . "\n";

/*
Receipt
-------
2 x Mechanical Keyboard @ $79.5
Subtotal: $159.00
Tax (8%): $12.72
TOTAL:    $171.72
*/

Notice the \$ escapes: inside double quotes a literal dollar sign must be escaped so PHP doesn't read it as the start of a variable name.

🎯 Quick Quiz

Question 1: What does 7 === "7" evaluate to in PHP?

Question 2: Which string will print the value of $name rather than the literal text?

Question 3: What is the idiomatic modern way to read $_GET['page'] with a default of 1?

Summary & Quiz

🎉 Key Takeaways

  • PHP code lives between <?php ... ?> tags; statements end in a semicolon.
  • Variables start with $, are case-sensitive, and are dynamically typed.
  • Core types: string, int, float, bool, array, null. Prefer === over ==.
  • Double quotes interpolate variables; single quotes are literal. Join strings with ..
  • Constants (const) name fixed values; ?? supplies defaults cleanly.

📚 Further Reading

🚀 What's Next?

Now that you can hold and manipulate data, the next lesson — Control Structures and Functions — shows how to make decisions, repeat work with loops, and package logic into reusable functions.

🎉 Great start!

You now speak PHP's basic grammar. Everything else in this module builds on these foundations.