PHP Get Started

PHP is a server-side scripting language built specifically for the web. When a visitor requests a page, PHP runs on the server, does whatever work you tell it to (read a database, do math, build HTML), and sends plain HTML back to the browser — the visitor never sees your PHP source code. This lesson gets you from zero to writing and understanding your very first PHP script, and explains what actually happens when PHP code runs.

Overview / How PHP Works

PHP (“PHP: Hypertext Preprocessor”) is an open-source, interpreted language. Unlike JavaScript in a browser, PHP code never reaches the client — it is executed entirely on the server by the Zend Engine, the C-based core that powers the standard PHP runtime. The typical flow for a web request looks like this:

  • A browser requests a URL such as example.com/index.php.
  • The web server (Apache, Nginx, or PHP’s own built-in server) recognizes the .php extension and hands the file to the PHP interpreter, usually through a process called PHP-FPM (FastCGI Process Manager).
  • The Zend Engine lexes the source into tokens, parses the tokens into an abstract syntax tree, and compiles that tree into low-level instructions called opcodes.
  • The engine executes the opcodes line by line, running any database queries, loops, or logic you wrote.
  • Any output your script produces (via echo, print, or plain HTML in the file) is streamed back to the web server, which sends it to the browser as a normal HTML response.

Because this all happens per-request, PHP does not keep your variables around between page loads (unless you use sessions, a database, or files) — every request starts a fresh, isolated execution of your script from top to bottom.

You can also run PHP without a web server at all, directly from the command line, which is the fastest way to practice. If PHP is installed, running php -v in a terminal prints the installed version, and php -S localhost:8000 starts a lightweight built-in development server rooted in the current folder — perfect for testing lessons like this one locally.

Syntax

Every block of PHP code lives inside special tags that tell the engine “everything between here is PHP, not plain text.”

<?php
    // your PHP code goes here
    echo "Hello, World!";
  • <?php — the opening tag. This is required and is the only opening tag you should rely on (short tags like <? are unreliable across configurations).
  • ?> — the closing tag. It is optional at the very end of a pure-PHP file, and modern style usually omits it to avoid accidental whitespace being sent to the browser.
  • ; — every statement ends with a semicolon, just like in C, Java, or JavaScript.
  • // or # — single-line comments. /* … */ — multi-line comments.
  • $ — every variable name starts with a dollar sign, e.g. $name.

Case sensitivity

Element Case-sensitive? Example
Variables Yes $name and $Name are different variables
Function names No strlen() and STRLEN() call the same function
Keywords (if, echo, function) No IF, If, and if all work
Class names No myClass and MyClass refer to the same class

Examples

Example 1: Your first script

<?php
$name = "Ada";
$year = 2026;

echo "Hello, " . $name . "!\n";
echo "Welcome to PHP in $year.\n";

Output:

Hello, Ada!
Welcome to PHP in 2026.

This script declares two variables, $name and $year, then prints two lines. Notice two ways of building strings: the dot (.) operator concatenates pieces together, while double-quoted strings can embed a variable directly, like "$year" — this is called string interpolation and only works inside double quotes, not single quotes.

Example 2: Variables, types, and simple math

<?php
$productName = "Keyboard";
$price = 49.99;
$inStock = true;
$quantity = 3;

$total = $price * $quantity;

echo "Product: $productName\n";
echo "Unit price: $" . $price . "\n";
echo "Quantity: $quantity\n";
echo "Total: $" . number_format($total, 2) . "\n";
echo "In stock: " . ($inStock ? "Yes" : "No") . "\n";

Output:

Product: Keyboard
Unit price: $49.99
Quantity: 3
Total: $149.97
In stock: Yes

PHP is dynamically typed — you never declare a variable’s type, the engine figures it out from the value assigned (a string, a float, a boolean, an integer). Here number_format() formats the float total to two decimal places, and the ternary operator ? : converts the boolean $inStock into a readable word.

Example 3: A small function with a match expression

<?php
function gradeLabel(int $score): string {
    return match (true) {
        $score >= 90 => "A",
        $score >= 80 => "B",
        $score >= 70 => "C",
        default => "F",
    };
}

$scores = [95, 82, 61];

foreach ($scores as $score) {
    echo "Score $score -> Grade " . gradeLabel($score) . "\n";
}

Output:

Score 95 -> Grade A
Score 82 -> Grade B
Score 61 -> Grade F

This example defines a typed function, gradeLabel(int $score): string, which uses PHP 8’s match expression to pick a grade based on the score. A foreach loop then walks over an array of scores, calling the function for each one. Type declarations like int and : string are optional in PHP but make your code far easier to reason about and let PHP throw a clear error if the wrong type is passed.

How It Works Step by Step

  • 1. Save the file with a .php extension, e.g. index.php.
  • 2. The engine reads the file and switches into “PHP mode” whenever it sees <?php, treating everything outside PHP tags as plain text to output verbatim.
  • 3. Lexing and parsing turn your code into tokens and then an abstract syntax tree, catching any syntax errors (like a missing semicolon) before anything runs.
  • 4. Compilation to opcodes — the AST becomes a sequence of Zend opcodes, PHP’s internal bytecode.
  • 5. Execution — the Zend Virtual Machine runs the opcodes top to bottom, allocating memory for variables, calling functions, and evaluating expressions.
  • 6. Output buffering — text from echo/print and any literal HTML is collected and sent to whatever is consuming the response (a browser, or your terminal when running via CLI).

Common Mistakes

Mistake 1: Forgetting the semicolon

Every statement needs a terminating semicolon. Leaving one off causes a parse error and the whole script fails to run.

<?php
$x = 5
echo $x;

PHP expects a semicolon after $x = 5 and instead finds echo, so it throws a parse error before any code executes. The fix is simple:

<?php
$x = 5;
echo $x;

Mistake 2: Using = instead of == in a condition

A single = is assignment, while == is comparison. Mixing them up is a classic bug because the code still runs — it just does the wrong thing.

<?php
$age = 15;
if ($age = 18) {
    echo "You are an adult.\n";
} else {
    echo "You are a minor.\n";
}

This prints “You are an adult.” even though $age was 15, because $age = 18 assigns 18 to $age and the assignment expression itself evaluates to 18, which is truthy. The corrected version compares instead of assigning:

<?php
$age = 15;
if ($age == 18) {
    echo "You are an adult.\n";
} else {
    echo "You are a minor.\n";
}

This correctly prints “You are a minor.” Many developers write comparisons as 18 == $age (constant first) specifically so a stray single = becomes an obvious fatal error instead of a silent bug.

Best Practices

  • Always end statements with a semicolon and use consistent indentation — readability matters as scripts grow.
  • Prefer === (strict comparison) over == when you care about both value and type, avoiding surprising type-juggling bugs.
  • Omit the closing ?> tag at the end of pure-PHP files to prevent accidental trailing whitespace from being sent as output.
  • Use meaningful variable names ($unitPrice, not $x) — PHP places no length limit on identifiers.
  • Turn on error reporting during development (error_reporting(E_ALL);) so mistakes surface immediately instead of failing silently in production.
  • Add type declarations to function parameters and return types where practical — they catch mistakes early and document intent.

Practice Exercises

  • Exercise 1: Write a script that declares variables for your favorite programming language and the year you started learning it, then echoes a sentence combining both using string interpolation.
  • Exercise 2: Write a function dayName(int $day): string that uses a match expression to convert a number 1–7 into a weekday name (1 = “Monday” … 7 = “Sunday”), then call it in a loop for the numbers 1 through 7.
  • Exercise 3: The following snippet has a bug: if ($count = 0) { echo "Empty"; } else { echo "Has items"; } where $count was previously set to 5. Identify the bug and rewrite it so it correctly reports “Has items”.

Summary

  • PHP code lives between <?php and an optional ?>, and every statement ends with a semicolon.
  • PHP runs entirely on the server: the Zend Engine lexes, parses, compiles to opcodes, and executes your script fresh on every request.
  • Variables start with $ and are case-sensitive; function and keyword names are not.
  • Double-quoted strings support variable interpolation; single-quoted strings do not.
  • Always double-check = (assignment) versus ==/=== (comparison) inside conditions — it’s one of the most common beginner bugs.
  • You can run PHP through a web server or directly via the command line (php -S localhost:8000) for quick local testing.