PHP Tutorial with Runnable Examples
A free PHP 8 tutorial and reference: arrays, foreach, string functions, dates, forms, classes and errors. Every example runs on the page, and examples that print HTML show the page, with forms you can submit.
Start a guided PHP journeyGetting Started
- What Is PHP?PHP is a server-side scripting language: a PHP file runs on the web server and sends the HTML it builds to the browser. It powers WordPress, Laravel and a large share of the web, and it also runs scripts from the command line.
- Install PHPInstall PHP with one command: winget on Windows, Homebrew on macOS, apt or dnf on Linux. Then run php -v in a terminal to check that it works and which version you have.
- Run PHPRun a PHP file from the terminal with php index.php, or serve a folder in the browser with PHP's built-in server: php -S localhost:8000. No Apache or XAMPP is needed for either.
- echo and printecho prints one or more strings: echo "Hello, $name"; or echo $a, $b;. It is the usual way to send text or HTML to the page. print does the same with one value and returns 1; <?= $x ?> is the short form inside HTML.
- Error ReportingTo show all PHP errors, put ini_set('display_errors', '1'); and error_reporting(E_ALL); at the top of the script, or set display_errors = On and error_reporting = E_ALL in php.ini. In production, log errors instead of displaying them.
- PHP vs PythonPHP is built for the web: a file runs per request and prints a page, and it powers WordPress and Laravel. Python is a general-purpose language that also does web work (Django, Flask) and dominates data science, automation and machine learning.
- PHP vs JavaScriptPHP runs on the server and sends finished HTML to the browser. JavaScript runs in the browser, where it changes the page after it loads, and on the server with Node.js. Most websites use both: PHP to build pages and APIs, JavaScript for interaction.
Basics
- VariablesA PHP variable starts with $ and is created by assigning to it: $name = "Ada";. There is no declaration keyword and no fixed type. Functions do not see outside variables unless you pass them in, use global, or capture them; static keeps a value between calls.
- Data TypesPHP has ten types: four scalars (int, float, string, bool), four compound types (array, object, callable, iterable) and two special ones (null, resource). var_dump($x) shows a value's type and value, gettype($x) returns the type name.
- StringsJoin PHP strings with the dot operator ("Hello, " . $name) or put variables straight into double quotes ("Hello, $name"). Single quotes print text as written. Learn concatenation, .=, interpolation of arrays and objects, and changing case with strtoupper, strtolower, ucfirst and ucwords.
- Heredoc and NowdocA PHP heredoc is a multiline string that starts with <<<EOT and ends with EOT; it replaces variables like a double-quoted string. A nowdoc, <<<'EOT', keeps the text exactly as written. Learn the syntax, indentation rules, interpolating arrays and objects, and HTML templates.
- OperatorsPHP operators work on values: +, -, *, /, %, ** for arithmetic, =, +=, .=, ??= for assignment, &&, ||, ! and xor for logic, . for joining strings, ==, ===, <=> for comparison and ++, -- for incrementing. Learn each group with runnable examples, plus the and vs && precedence trap.
- Comparison OperatorsPHP compares values with == (equal after type juggling), === (equal value and same type), != and !==, < > <= >= and the spaceship operator <=>. Learn when == converts types, what changed in PHP 8, and see every loose and strict comparison in one table.
- Ternary OperatorThe PHP ternary operator is a one-line if/else: $result = $condition ? 'yes' : 'no';. Learn the short ternary ?: (Elvis operator), how it differs from ??, why nested ternaries need parentheses since PHP 8, and when match is the cleaner choice.
- Null Coalescing ??The PHP null coalescing operator returns its left side unless it is null or not set: $name = $_GET['name'] ?? 'Guest';. It never warns about a missing variable or array key. Learn ?? chains, the ??= assignment, ?? vs ?:, and the nullsafe operator ?->.
- Type CastingConvert a PHP string to an integer with (int) $str or intval($str); (int) "42" is 42 and (int) "12abc" is 12. Learn casting to int, float, bool, string and array, numeric strings, intval with a base, settype, and how to validate input instead of silently getting 0.
- ConstantsA PHP constant is a name for a value that cannot change: const MAX_USERS = 100; or define('MAX_USERS', 100);. Learn define vs const, constant arrays, class constants with self::, checking with defined(), and the magic constants __LINE__, __FILE__, __DIR__ and __CLASS__.
- isset()isset($var) returns true when a variable exists and is not null, and false otherwise, without any warning. It also checks array keys and object properties: isset($user['email']). Learn isset with several variables, nested keys, isset vs empty, isset vs array_key_exists, and checking form submissions.
- empty()empty($var) returns true when a variable is missing or falsy: null, false, 0, 0.0, "", "0" or []. It never warns about undefined variables or keys. Learn why "0" counts as empty, how to check for an empty string or array exactly, empty vs isset, and validating form input.
- Math and Roundinground($x, 2) rounds to two decimal places, floor() always rounds down and ceil() always rounds up. Also intdiv(), the % operator, ** for powers, abs(), max(), min() and random_int() for random numbers.
Control Flow
- if, elseif, elseif (condition) { ... } runs a block only when the condition is true, elseif checks the next condition, and else runs when none matched. Covers elseif vs else if, && and ||, truthy values and the if: endif; syntax for HTML templates.
- switch Statementswitch ($value) compares one value against a list of case labels and runs the code from the first match until a break. Covers multiple cases, fallthrough, default, switch(true), and why switch uses loose == comparison.
- match Expressionmatch ($x) { 1, 2 => 'low', default => 'other' } compares a value with strict ===, returns the result of the first matching arm, and throws an UnhandledMatchError when nothing matches. Covers match vs switch, match(true) and match with enums.
- for Loopfor ($i = 0; $i < 10; $i++) { ... } runs a block a set number of times: start value, condition checked before each pass, and a step. Covers looping through an array by index, counting down, nested loops, break and continue.
- while Loopwhile (condition) { ... } repeats a block as long as the condition is true, checking it before every pass. do { ... } while (condition); checks after, so it always runs at least once. Covers while (true) with break, reading a file line by line, and avoiding infinite loops.
- foreach Loopforeach ($array as $value) visits every element of an array, and foreach ($array as $key => $value) gives you the key too. Covers getting the index, changing values by reference and the unset() gotcha, break and continue, nested arrays, list() in foreach, and building HTML.
Arrays
- ArraysA PHP array is an ordered list of values, each stored under a key: $fruits = ['apple', 'banana']; reads as $fruits[0]. Learn how to create arrays, read and change elements, loop over them, print them, and which array function to reach for.
- Associative ArraysA PHP associative array stores values under keys you name: $user = ['name' => 'Ada', 'age' => 36]; reads as $user['name']. Learn how to add, change and remove pairs, loop over keys and values, get all keys or values, check a key, and sort by key or value.
- Multidimensional ArraysA multidimensional array in PHP is an array whose elements are arrays, read with one bracket per level: $grid[1][2] or $users[0]['name']. Learn how to create nested arrays, read and change deep values, loop with nested foreach, build an HTML table, pull out a column and sort rows.
- array_push()array_push($arr, $value) adds one or more values to the end of an array; $arr[] = $value does the same for one value and is faster. Learn how to add to the end, the beginning or the middle of an array, add a key and value, and avoid the classic return-value bug.
- count()count($arr) returns the number of elements in a PHP array, so count(['a', 'b', 'c']) is 3. Learn how to count nested arrays with COUNT_RECURSIVE, how sizeof() relates to count(), how to count matching values, and why count(null) throws a TypeError since PHP 8.
- in_array()in_array($needle, $haystack) returns true when the value is in the array. Pass true as the third argument for a strict check, in_array('1', $ids, true), so that types must match too. Learn the strict flag, case-insensitive searches, checking several values, nested arrays, and the fast isset alternative.
- array_search()array_search($value, $array) returns the key of the first element equal to $value, or false when there is none. Because the key can be 0, always test the result with !== false. Learn strict searches, finding every match, searching a multidimensional array with array_column, and case-insensitive searches.
- array_key_exists()array_key_exists('key', $array) returns true when the array has that key, even if its value is null. isset($array['key']) is faster but returns false for a null value. Learn the difference, key_exists(), nested keys, checking several keys, and why objects need property_exists().
- array_merge()array_merge($a, $b) joins arrays into one: values with numeric keys are appended and renumbered, and for string keys the later array wins. Learn how array_merge differs from the + operator and the spread syntax [...$a, ...$b], how to merge a list of arrays, and when array_merge_recursive or array_replace fits better.
- array_map()array_map($callback, $array) calls the callback on every element and returns a new array of the results. Learn arrow functions, keys, mapping several arrays at once, and when array_walk or foreach fits better.
- array_filter()array_filter($array, $callback) keeps the elements for which the callback returns true. Learn how to remove empty values, filter by key with ARRAY_FILTER_USE_KEY, reindex the result with array_values, and add things up with array_reduce.
- Sorting Arrayssort($array) sorts a list in place, asort and ksort sort an associative array by value or by key, and usort sorts with your own comparison. Learn all of them, sort a multidimensional array by a column, and avoid the classic $sorted = sort($arr) mistake.
- Remove from Arrayunset($array[$key]) removes an element by key, array_splice removes by position and renumbers, and array_diff removes by value. Learn each one, how to reindex afterwards, and the array_search pitfall that deletes the wrong element.
- array_slice()array_slice($array, $offset, $length) returns a copy of part of an array without changing the original. Learn negative offsets for the last items, preserve_keys, paging through a list, and how it differs from array_splice.
- array_unique()array_unique($array) removes duplicate values and keeps the first occurrence of each, with its original key. Learn how to reindex the result, remove duplicates ignoring case, make a multidimensional array unique, and count or find the duplicates.
- array_column()array_column($rows, 'email') returns the email field of every row as a flat array. Learn the index key argument, reindexing rows by id, using it with objects, and finding a row with array_search.
- Destructuring and list()[$a, $b] = $array assigns the first two elements to $a and $b in one line, and ['name' => $name] = $user does the same by key. list() is the older spelling. Covers skipping elements, swapping variables, multiple return values, destructuring in foreach and the ... spread operator.
Strings
- explode()explode(',', $string) splits a string at every comma and returns the pieces as an array. Learn the limit parameter, splitting by newline, trimming the pieces, and when str_split or preg_split is the better tool.
- implode()implode(', ', $array) joins the values of an array into one string with a separator between them. Learn implode with keys, associative arrays, building HTML lists, and the difference between implode and join.
- str_replace()str_replace($search, $replace, $subject) replaces every occurrence of $search with $replace. Learn arrays of search and replace values, counting replacements, case-insensitive str_ireplace, and replacing only the first occurrence.
- substr()substr($string, $offset, $length) returns part of a string. Learn negative offsets, getting the first or last characters, mb_substr for Japanese and other UTF-8 text, substr_count, and cutting text with an ellipsis.
- strpos()strpos($haystack, $needle) returns the position of the first occurrence of $needle, or false if it is not found. Learn the !== false check, case-insensitive stripos, the last match with strrpos, and finding every occurrence.
- str_contains()str_contains($haystack, $needle) returns true if $needle appears anywhere in $haystack. Learn the case-insensitive version, str_starts_with and str_ends_with, checking for several words, and the strpos version for PHP 7.
- trim()trim($string) removes spaces, tabs and newlines from both ends of a string; ltrim() and rtrim() clean one side. Learn how to trim specific characters, the full-width Japanese space, and every value in an array.
- strlen()strlen($string) returns the length of a string in bytes; mb_strlen($string) returns it in characters. Learn why Japanese text and emoji give different answers, how to check for an empty string, and how to validate input length.
- sprintf()sprintf() builds a string from a format and values: sprintf('%05.2f', 3.14159) returns "03.14". Learn %s, %d and %f, zero padding, fixed decimals, alignment, argument numbering, printf and vsprintf.
- number_format()number_format(1234567.891, 2) returns "1,234,567.89": it rounds to the given decimals and adds a thousands separator. Learn the four parameters, European and Japanese formats, how it rounds, and why the result is a string.
- NewlinesTo print a new line in PHP, write "\n" inside double quotes or use PHP_EOL. In a web page a newline is not visible, so use <br> or nl2br(). Learn the difference, why '\n' in single quotes does not work, and how to split or remove line breaks.
- preg_match()preg_match($pattern, $subject, $matches) tests a string against a regular expression and returns 1 for a match, 0 for none. Learn capture groups, named groups, preg_match_all, anchors, validation patterns and the u modifier for UTF-8 and Japanese text.
- preg_replace()preg_replace($pattern, $replacement, $subject) replaces every match of a regular expression: preg_replace('/\s+/', ' ', $text) collapses whitespace. Learn backreferences like $1, preg_replace_callback, removing non-alphanumeric characters, limits and counts.
Functions
- FunctionsDefine a PHP function with function name($param) { return $value; }. Learn return values, default parameters, named arguments, passing by reference, type declarations with strict_types, nullable and union types, and variadic ...$args.
- Arrow FunctionsAn arrow function is a one-expression anonymous function written fn($x) => $x * 2. It uses outer variables automatically, by value, without use. Learn the syntax, how capturing works, types, callbacks for array_map and usort, and when to use a full closure instead.
- Anonymous FunctionsAn anonymous function (closure) is a function without a name stored in a variable: $greet = function ($name) { return "Hi $name"; };. Learn the use keyword, capturing by reference, callables, first-class callable syntax strlen(...) and closures inside classes.
- GeneratorsA generator is a function that uses yield to hand back values one at a time, so foreach can loop over a million items without building an array. Learn yield, keys, memory savings, infinite sequences, yield from, send() and getReturn().
Classes and Objects
- Classes and ObjectsA PHP class is a blueprint declared with `class Name { }`, and `new Name()` creates an object from it. Learn properties, methods, `$this`, public/private/protected, typed and readonly properties, `__toString`, and why assigning an object does not copy it.
- ConstructorsA PHP constructor is the `__construct()` method, which runs automatically when you write `new ClassName(...)`. Learn constructor property promotion, default and named arguments, validation, `parent::__construct()`, and how to fake multiple constructors with static factory methods.
- InheritanceIn PHP a class inherits from another with `class Dog extends Animal`: it gets the parent's public and protected properties and methods, can override them, and can still call the original with `parent::method()`. Learn overriding, protected, final, instanceof and the private method trap.
- InterfacesA PHP interface lists methods a class promises to have: `interface Shape { public function area(): float; }`, and `class Circle implements Shape` must then define `area()`. Learn type hints with interfaces, implementing several interfaces, interface constants, extending interfaces, built-in interfaces like Countable, and interface vs abstract class.
- Abstract ClassesA PHP abstract class is declared `abstract class Name` and cannot be instantiated: it exists to be extended. It can hold properties, a constructor and finished methods, plus `abstract` methods with no body that every child class must implement.
- TraitsA PHP trait is a reusable block of methods and properties that you copy into a class with `use TraitName;`. Learn using several traits, resolving name conflicts with `insteadof` and `as`, abstract and static trait members, which method wins, and trait vs interface vs abstract class.
- EnumsA PHP enum (8.1+) is a type with a fixed list of values: `enum Status: string { case Active = 'active'; }`. Learn pure and backed enums, `->value` and `->name`, converting with `from()` and `tryFrom()`, listing cases with `cases()`, methods, constants, interfaces, and enums in `match`.
- Static MethodsA `static` method or property belongs to the class, not to an object: you call it with `ClassName::method()` and read it with `ClassName::$count`, no `new` needed. Learn `self::` vs `static::` (late static binding), `new static`, static variables inside functions, and when static is the wrong tool.
- NamespacesA PHP namespace groups classes, functions and constants under a prefix: `namespace App\Models;` at the top of a file, then `use App\Models\User;` elsewhere to refer to the class by its short name. Learn fully qualified names, `use ... as` aliases, `use function`, the leading backslash for global classes, and PSR-4 autoloading.
Errors and Exceptions
- try catchIn PHP, code that might fail goes in a `try { }` block, and `catch (Exception $e) { }` runs if it throws, with the reason in `$e->getMessage()`. Learn catching several exception types, `finally`, why `catch (Exception)` misses `TypeError` and `DivisionByZeroError` (catch `Throwable`), rethrowing, and a global handler.
- ExceptionsYou throw an exception in PHP with `throw new Exception('message');`, and the caller reads it with `$e->getMessage()` in a `catch` block. Learn the built-in exception classes, writing custom exceptions, `getCode()`, `getLine()` and `getPrevious()`, `throw` as an expression, and the errors PHP throws itself such as `ValueError` and `TypeError`.
Data, Files and the Web
- json_encode()json_encode($value) turns a PHP array, object or scalar into a JSON string. Associative arrays become JSON objects, lists become JSON arrays, and flags such as JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE control the output.
- json_decode()json_decode($json, true) turns a JSON string into a PHP associative array; without true you get stdClass objects. Learn nested values, error handling with JSON_THROW_ON_ERROR, json_validate() and why json_decode returns null.
- date()date('Y-m-d') returns today's date as a string, and date('Y-m-d', $timestamp) formats any Unix timestamp. Learn time(), mktime(), strtotime(), DateTimeImmutable, adding days, the difference between two dates and timezones, with examples you can run.
- Date FormatA PHP date format is a string of letters such as 'Y-m-d H:i:s', where Y is the 4-digit year, m the month, d the day, H the hour, i the minutes and s the seconds. Here is every format character with an example, plus escaping, ISO 8601, Japanese dates and converting one format to another.
- file_get_contents()file_get_contents('notes.txt') reads a whole file and returns it as one string, or false if it cannot. Its partner file_put_contents() writes a string to a file, and file() returns the lines as an array.
- fopen()fopen('data.txt', 'r') opens a file and returns a handle, or false on failure. Read from the handle with fgets() or fread(), write with fwrite(), close it with fclose(). The mode ('r', 'w', 'a', 'x', 'c' and their + forms) decides what you can do.
- include and requireinclude 'header.php'; runs another PHP file at that point, as if its code were pasted in. require does the same but stops the script with a fatal error when the file is missing, while include only warns and carries on. include_once and require_once load a file only the first time.
- FormsA PHP form posts to itself with <form method="post">, and the script reads the fields from $_POST['name'] once $_SERVER['REQUEST_METHOD'] is 'POST'. Learn validation, error messages next to fields, keeping entered values, checkboxes and selects, and escaping output.
- $_GET and $_POST$_GET holds the query string of the URL (?page=2 gives $_GET['page']) and $_POST holds the fields of a form sent with method="post". Learn to read both safely, build links with http_build_query, check $_SERVER['REQUEST_METHOD'], and choose between GET and POST.
- htmlspecialchars()htmlspecialchars($text) turns the five characters that mean something in HTML (& < > " ') into entities, so user input is shown as text instead of running as markup. Learn ENT_QUOTES, escaping attributes, double encoding, htmlentities and strip_tags.
- Sessions and CookiesCall session_start() at the top of every page, then store values in $_SESSION['key']; PHP keeps them on the server and remembers the visitor through a cookie. setcookie('name', 'value', $options) stores a small value in the browser, read back from $_COOKIE. Learn login, logout, flash messages, cookie options and the security settings.
- password_hash()Hash a password with password_hash($password, PASSWORD_DEFAULT), store the 60-character result, and check a login with password_verify($password, $hash). Learn why the hash changes every time, cost, password_needs_rehash, Argon2id, and why md5 and sha1 are wrong for passwords.
- filter_var()filter_var($value, FILTER_VALIDATE_EMAIL) returns the value if it is valid and false if not; FILTER_VALIDATE_INT, FILTER_VALIDATE_URL, FILTER_VALIDATE_BOOL and FILTER_VALIDATE_IP work the same way. Learn the options (min_range, default), flags, sanitize filters and the false vs 0 trap.
- PDOPDO is PHP's database layer: connect with new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', $user, $pass), then run every query with values through prepare() and execute([$value]). Learn connecting, prepared statements, fetching rows, inserts, transactions and WHERE IN.
- ComposerComposer is PHP's package manager: composer require vendor/package downloads a library into vendor/, records it in composer.json, and require 'vendor/autoload.php' loads it. Learn to install Composer, composer.json, version constraints, install vs update, and PSR-4 autoloading for your own classes.
Debugging and Practice
- var_dump() and print_r()print_r($array) prints an array in a readable form, var_dump($value) also shows every type and length, and var_export prints valid PHP code. Learn when to use each, how to get print_r as a string, and how to pretty print in HTML with <pre>.
- Interview Questions24 PHP interview questions with short, correct answers for PHP 8, from == vs === and isset vs empty to references in foreach, self vs static, generators, SQL injection and password hashing. Most answers have code you can run and change.