Getting started
Introduction
PHP is a popular server-side scripting language designed for web development. This guide covers PHP 7+ with modern features including type declarations, return types, and PHP 8 enhancements.
Hello World
<?php
echo "Hello, World!";
?>
Variables
$name = "John";
$age = 30;
$price = 19.99;
$isActive = true;
Variables start with $ followed by the variable name.
Basic Types
| Type | Example |
|---|---|
int |
42 |
float |
3.14 |
string |
"Hello" |
bool |
true, false |
array |
[1, 2, 3] |
object |
new stdClass() |
null |
null |
Type Declarations
Function Type Hints
function greet(string $name): string {
return "Hello, $name";
}
function add(int $a, int $b): int {
return $a + $b;
}
function getUser(int $id): ?User {
return $user ?? null;
}
Use ?Type for nullable return types.
Strict Types
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
add(1, 2); // OK
add("1", "2"); // TypeError
Union Types (PHP 8+)
function process(int|float $value): int|float {
return $value * 2;
}
function find(int $id): User|null {
return $user ?? null;
}
Multiple types separated by |.
Arrays
Indexed Arrays
$fruits = ["apple", "banana", "orange"];
$numbers = [1, 2, 3, 4, 5];
echo $fruits[0]; // "apple"
echo $numbers[2]; // 3
Zero-indexed arrays using [] syntax.
Associative Arrays
$user = [
"name" => "John",
"email" => "john@example.com",
"age" => 30
];
echo $user["name"]; // "John"
Key-value pairs with => operator.
Array Functions
count($array) // Length
array_push($arr, $val) // Add to end
array_pop($arr) // Remove from end
in_array($val, $arr) // Check existence
explode(",", $str) // String to array
implode(",", $arr) // Array to string
Control Structures
If/Else
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teenager";
} else {
echo "Child";
}
Standard conditional statements.
Switch
switch ($day) {
case "Monday":
echo "Start of week";
break;
case "Friday":
echo "TGIF!";
break;
default:
echo "Regular day";
}
Use break to prevent fall-through.
Match (PHP 8+)
$result = match ($status) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown"
};
Expression-based, no fall-through needed.
Ternary & Null Coalescing
// Ternary
$msg = $isLoggedIn ? "Welcome" : "Login";
// Null coalescing
$name = $_GET["name"] ?? "Guest";
$val = $a ?? $b ?? $c ?? "default";
?? returns first non-null value.
Loops
For Loop
for ($i = 0; $i < 10; $i++) {
echo $i;
}
for ($i = 10; $i > 0; $i--) {
echo $i;
}
Standard counting loops.
Foreach
// Indexed array
foreach ($fruits as $fruit) {
echo $fruit;
}
// Associative array
foreach ($user as $key => $value) {
echo "$key: $value";
}
Iterate over arrays and objects.
While & Do-While
// While
while ($i < 10) {
echo $i;
$i++;
}
// Do-While
do {
echo $i;
$i++;
} while ($i < 10);
do-while executes at least once.
Functions
Basic Functions
function greet($name) {
return "Hello, $name";
}
echo greet("World");
Functions defined with function keyword.
Default Parameters
function greet($name = "Guest") {
return "Hello, $name";
}
echo greet(); // "Hello, Guest"
echo greet("John"); // "Hello, John"
Default values for optional parameters.
Variadic Functions
function sum(...$numbers): int {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
...$param accepts variable arguments.
Arrow Functions (PHP 7.4+)
$multiply = fn($x, $y) => $x * $y;
echo $multiply(5, 3); // 15
// With array functions
$doubled = array_map(
fn($n) => $n * 2,
[1, 2, 3, 4]
);
Short syntax for simple functions.
Classes & OOP
Basic Class
class User {
public string $name;
private int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function greet(): string {
return "Hello, {$this->name}";
}
}
$user = new User("John", 30);
echo $user->greet();
Classes with properties and methods.
Visibility
class Example {
public $pub = "public";
protected $pro = "protected";
private $pri = "private";
public function test() {
// All accessible here
}
}
| Visibility | Access |
|---|---|
public |
Everywhere |
protected |
Class + children |
private |
Class only |
Inheritance
class Animal {
public function speak(): string {
return "Some sound";
}
}
class Dog extends Animal {
public function speak(): string {
return "Woof!";
}
}
$dog = new Dog();
echo $dog->speak(); // "Woof!"
Use extends for inheritance.
Interfaces
interface Drawable {
public function draw(): void;
}
class Circle implements Drawable {
public function draw(): void {
echo "Drawing circle";
}
}
Contracts that classes must implement.
Traits
trait Loggable {
public function log(string $msg): void {
echo "[LOG] $msg";
}
}
class User {
use Loggable;
}
$user = new User();
$user->log("Hello");
Reusable methods across classes.
Static Members
class Config {
public static string $version = "1.0";
public static function get(): string {
return self::$version;
}
}
echo Config::$version; // "1.0"
echo Config::get(); // "1.0"
Access with :: operator and self.
Namespaces
Declaring Namespaces
<?php
namespace App\Models;
class User {
// ...
}
Organize code into logical groups.
Using Namespaces
use App\Models\User;
use App\Services\UserService as Service;
$user = new User();
$service = new Service();
Import with use and alias with as.
Fully Qualified Names
$user = new \App\Models\User();
// Current namespace
$local = new User();
// Global namespace
$datetime = new \DateTime();
\ prefix for fully qualified names.
Exception Handling
Try/Catch/Finally
try {
$result = riskyOperation();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
cleanup();
}
finally always executes.
Multiple Catch Blocks
try {
// code
} catch (PDOException $e) {
echo "Database error";
} catch (InvalidArgumentException $e) {
echo "Invalid argument";
} catch (Exception $e) {
echo "General error";
}
Catch specific exceptions first.
Throwing Exceptions
function divide(int $a, int $b): float {
if ($b === 0) {
throw new InvalidArgumentException(
"Cannot divide by zero"
);
}
return $a / $b;
}
Use throw to raise exceptions.
Superglobals
$_GET & $_POST
// GET: /page.php?name=John&age=30
$name = $_GET["name"] ?? "Guest";
$age = $_GET["age"] ?? 0;
// POST form data
$username = $_POST["username"] ?? "";
$password = $_POST["password"] ?? "";
HTTP request data.
$_SERVER
$_SERVER["REQUEST_METHOD"] // "GET", "POST"
$_SERVER["HTTP_HOST"] // Domain
$_SERVER["REQUEST_URI"] // Current URL
$_SERVER["REMOTE_ADDR"] // Client IP
$_SERVER["HTTP_USER_AGENT"] // Browser info
Server and request information.
$_SESSION & $_COOKIE
// Session
session_start();
$_SESSION["user_id"] = 123;
$userId = $_SESSION["user_id"] ?? null;
// Cookie
setcookie("theme", "dark", time() + 3600);
$theme = $_COOKIE["theme"] ?? "light";
State management across requests.
$_FILES
if (isset($_FILES["upload"])) {
$file = $_FILES["upload"];
$name = $file["name"];
$tmpName = $file["tmp_name"];
$size = $file["size"];
$error = $file["error"];
move_uploaded_file($tmpName, "uploads/$name");
}
Uploaded file handling.
Database (PDO)
Connection
$dsn = "mysql:host=localhost;dbname=mydb";
$username = "root";
$password = "secret";
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
Always use PDO for database operations.
Prepared Statements
// SELECT
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// INSERT
$stmt = $pdo->prepare(
"INSERT INTO users (name, email) VALUES (?, ?)"
);
$stmt->execute([$name, $email]);
// Named parameters
$stmt = $pdo->prepare(
"UPDATE users SET name = :name WHERE id = :id"
);
$stmt->execute(["name" => $name, "id" => $id]);
Prevents SQL injection attacks.
Fetch Methods
// Single row
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// All rows
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Single column
$name = $stmt->fetchColumn();
// Loop through results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row["name"];
}
Different ways to retrieve results.
String Functions
Common Operations
strlen($str) // Length
strtoupper($str) // To uppercase
strtolower($str) // To lowercase
ucfirst($str) // Capitalize first
ucwords($str) // Capitalize words
str_replace($find, $replace, $str)
substr($str, $start, $length)
strpos($str, $needle) // Find position
trim($str) // Remove whitespace
String Splitting
// String to array
$parts = explode(",", "a,b,c");
// ["a", "b", "c"]
// Array to string
$str = implode(", ", ["a", "b", "c"]);
// "a, b, c"
// Split into characters
$chars = str_split("hello");
// ["h", "e", "l", "l", "o"]
Convert between strings and arrays.
String Interpolation
$name = "John";
$age = 30;
// Double quotes
echo "Name: $name, Age: $age";
// Curly braces for clarity
echo "User: {$user['name']}";
// Concatenation
echo 'Name: ' . $name . ', Age: ' . $age;
Double quotes parse variables.
Array Functions
Adding/Removing
// Add to end
array_push($arr, $val);
$arr[] = $val; // Shorthand
// Add to start
array_unshift($arr, $val);
// Remove from end
$val = array_pop($arr);
// Remove from start
$val = array_shift($arr);
Modify arrays in place.
Searching & Filtering
in_array($needle, $haystack) // Check existence
array_search($needle, $haystack) // Find key
// Filter
$even = array_filter($arr, fn($n) => $n % 2 === 0);
// Map
$doubled = array_map(fn($n) => $n * 2, $arr);
// Reduce
$sum = array_reduce($arr, fn($carry, $n) => $carry + $n, 0);
Functional array operations.
Array Utilities
count($arr) // Length
array_keys($arr) // Get all keys
array_values($arr) // Get all values
array_merge($arr1, $arr2) // Combine arrays
array_reverse($arr) // Reverse order
array_unique($arr) // Remove duplicates
sort($arr) // Sort ascending
rsort($arr) // Sort descending
asort($arr) // Sort keeping keys
File Operations
Reading Files
// Read entire file
$content = file_get_contents("file.txt");
// Read as array (line by line)
$lines = file("file.txt");
// Open and read
$handle = fopen("file.txt", "r");
while ($line = fgets($handle)) {
echo $line;
}
fclose($handle);
Multiple ways to read files.
Writing Files
// Write (overwrite)
file_put_contents("file.txt", $content);
// Append
file_put_contents("file.txt", $content, FILE_APPEND);
// Open and write
$handle = fopen("file.txt", "w");
fwrite($handle, $content);
fclose($handle);
Write content to files.
File Checks
file_exists($path) // File exists?
is_file($path) // Is regular file?
is_dir($path) // Is directory?
is_readable($path) // Can read?
is_writable($path) // Can write?
filesize($path) // Get size in bytes
Check file properties.
Date & Time
Current Date/Time
// Format current time
echo date("Y-m-d H:i:s"); // 2026-02-06 14:30:00
// Timestamp
$timestamp = time();
// DateTime object
$dt = new DateTime();
echo $dt->format("Y-m-d H:i:s");
Work with dates and times.
Formatting
| Format | Output |
|---|---|
Y-m-d |
2026-02-06 |
d/m/Y |
06/02/2026 |
H:i:s |
14:30:00 |
F j, Y |
February 6, 2026 |
l |
Friday |
Date Manipulation
$dt = new DateTime("2026-02-06");
// Add time
$dt->modify("+1 day");
$dt->modify("+3 months");
$dt->modify("-2 hours");
// Set timezone
$dt->setTimezone(new DateTimeZone("UTC"));
// Compare dates
$dt1 = new DateTime("2026-02-06");
$dt2 = new DateTime("2026-03-01");
$diff = $dt1->diff($dt2);
echo $diff->days; // Days between
DateTime object manipulation.
JSON Handling
Encoding
$data = [
"name" => "John",
"age" => 30,
"active" => true
];
$json = json_encode($data);
// {"name":"John","age":30,"active":true}
// Pretty print
$json = json_encode($data, JSON_PRETTY_PRINT);
Convert PHP to JSON.
Decoding
$json = '{"name":"John","age":30}';
// As associative array
$data = json_decode($json, true);
echo $data["name"]; // "John"
// As object
$obj = json_decode($json);
echo $obj->name; // "John"
Convert JSON to PHP.
Error Handling
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
}
Check for JSON parsing errors.
Useful Patterns
Null Coalescing Chain
// Get first non-null value
$value = $_GET["key"]
?? $_POST["key"]
?? $_SESSION["key"]
?? $default;
Graceful fallback chains.
Spaceship Operator
// Returns -1, 0, or 1
echo 1 <=> 2; // -1
echo 2 <=> 2; // 0
echo 3 <=> 2; // 1
// Useful for sorting
usort($arr, fn($a, $b) => $a <=> $b);
Three-way comparison for sorting.
Array Destructuring
// List syntax
[$a, $b, $c] = [1, 2, 3];
// With keys
["name" => $name, "age" => $age] = $user;
// In foreach
foreach ($users as ["name" => $name, "age" => $age]) {
echo "$name is $age years old";
}
Extract array values into variables.
Gotchas
Type Juggling
// PHP auto-converts types
"5" + 3 // 8 (string → int)
"5 apples" + 3 // 8 (parses leading number)
true + 1 // 2 (bool → int)
// Use strict comparison
"0" == false // true (type juggling)
"0" === false // false (strict)
Use === for strict comparison.
Variable Variables
$var = "name";
$$var = "John";
echo $name; // "John"
// Avoid this pattern - use arrays instead
$data["name"] = "John";
Confusing and hard to debug.
Include vs Require
// Include (continues on error)
include "file.php";
// Require (fatal error)
require "file.php";
// Include once
include_once "file.php";
require_once "file.php";
require for critical files.
Also see
- PHP Official Documentation - Official PHP manual
- PHP: The Right Way - Best practices guide
- Composer - Dependency manager for PHP
- PSR Standards - PHP coding standards
- GitHub Issue #75 - Original request