PHP Documentation
The server-side language behind WordPress and a huge part of the web — forms, sessions and databases.
PHP is a server-side scripting language built for the web. It runs on the server, generates HTML, handles forms, sessions and databases, and powers WordPress, Laravel apps and a large part of the internet. Modern PHP (8.x) is fast, has types, classes, enums and a great package manager — Composer.
1. Introduction & Installation
- Windows: install XAMPP (PHP + Apache + MySQL), or download PHP from windows.php.net and add it to PATH.
- macOS:
brew install php. Linux:sudo apt install php-cli.
php -v
php hello.php # run a script in the terminal
php -S localhost:8000 # built-in web server for the current folder
<?php
echo "Hello, Codify!\n";
Output:
Hello, Codify!
PHP code lives between <?php and ?> and can be mixed with HTML:
<!-- index.php -->
<h1>Welcome</h1>
<p>Today is <?= date('l') ?>.</p>
⚠️ Common error: opening a
.phpfile directly in the browser (file:///...) shows the source code. PHP must run through a server — usephp -S localhost:8000and openhttp://localhost:8000.
2. Basic Syntax
- Statements end with
;. Variables start with$and are case-sensitive. echo/printoutput text. Strings in double quotes expand variables; single quotes don't.- Comments:
//,#and/* */.
<?php
$name = "Asha";
$age = 20;
echo "Hello $name, you are $age\n";
echo 'Single quotes: $name' . "\n"; // . joins strings
echo "Next year: {$age}+1 = " . ($age + 1) . "\n";
printf("%s scored %.1f%%\n", $name, 92.456);
Output:
Hello Asha, you are 20
Single quotes: $name
Next year: 20+1 = 21
Asha scored 92.5%
⚠️ Common error:
Parse error: syntax error, unexpected ...usually means a missing;on the previous line.
3. Variables & Data Types
PHP is dynamically typed. Types: int, float, string, bool, array, object, null, plus callable and iterable.
<?php
$count = 42;
$price = 19.99;
$title = "Codify";
$isActive = true;
$nothing = null;
$tags = ["php", "web"];
const SITE = "codify";
var_dump($count, $price, $isActive, $nothing);
echo gettype($tags), " ", strlen($title), " ", SITE, "\n";
echo intval("12abc") + 1, " ", (int) "7" * 2, " ", 10 / 4, " ", intdiv(10, 4), " ", 10 % 4, "\n";
echo PHP_INT_MAX, "\n";
Output:
int(42)
float(19.99)
bool(true)
NULL
array 6 codify
13 14 2.5 2 2
9223372036854775807
You can add type declarations to functions and enable strict mode with declare(strict_types=1); at the top of a file.
⚠️ Common error:
Warning: Undefined variable $x— the variable was never assigned (check spelling —$Name≠$name).
4. Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / % ** |
| String | . (concatenate), .= |
| Comparison | == (loose), === (strict: value and type), !=, !==, <=> (spaceship) |
| Logical | &&, ` |
| Null | ?? (null coalescing), ??=, ?-> (nullsafe) |
| Assignment | = += -= *= /= .= |
<?php
var_dump(0 == "a", "1" == "01", 100 == "1e2", 1 === "1");
echo 5 <=> 3, " ", 2 <=> 2, " ", 1 <=> 9, "\n";
$user = null;
echo $_GET['page'] ?? "home", " ", $user?->name ?? "guest", "\n";
$s = "Cod";
$s .= "ify";
echo $s, " ", 2 ** 10, "\n";
Output:
bool(false)
bool(true)
bool(true)
bool(false)
1 0 -1
home guest
Codify 1024
⚠️ Common error: using
==for comparisons that must also match type ("abc" == 0wastruebefore PHP 8). Prefer===.
5. Conditional Statements
<?php
$marks = 82;
if ($marks >= 90) {
echo "A\n";
} elseif ($marks >= 75) {
echo "B\n";
} else {
echo "C\n";
}
$day = "sat";
switch ($day) {
case "sat":
case "sun":
echo "Weekend\n";
break;
default:
echo "Weekday\n";
}
$status = 404;
echo match (true) { // match expression (PHP 8)
$status >= 500 => "server error",
$status >= 400 => "client error",
default => "ok",
}, "\n";
echo $marks >= 40 ? "pass" : "fail", "\n";
Output:
B
Weekend
client error
pass
⚠️ Common error: an unmatched value in
matchthrowsUnhandledMatchError— add adefaultarm.
6. Loops
<?php
for ($i = 1; $i <= 5; $i++) echo $i, " ";
echo "\n";
$fruits = ["apple", "mango", "kiwi"];
foreach ($fruits as $index => $fruit) echo "$index: $fruit\n";
$marks = ["asha" => 91, "ravi" => 78];
foreach ($marks as $name => $m) echo "$name scored $m\n";
$n = 1;
while ($n < 100) $n *= 3;
echo "n = $n\n";
$k = 0;
do { $k++; } while ($k < 3);
echo "k = $k\n";
Output:
1 2 3 4 5
0: apple
1: mango
2: kiwi
asha scored 91
ravi scored 78
n = 243
k = 3
⚠️ Common error:
foreach ($arr as &$v)keeps$vas a reference after the loop — modifying$vlater changes the last element.unset($v)after such loops.
7. Functions
<?php
declare(strict_types=1);
function add(int $a, int $b = 10): int { // typed params, default value
return $a + $b;
}
function total(float ...$prices): float { // variadic
return array_sum($prices);
}
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
$square = fn(int $x): int => $x * $x; // arrow function
$tax = 0.18;
$withTax = function (float $p) use ($tax): float { // closure capturing $tax
return round($p * (1 + $tax), 2);
};
echo add(5), " ", total(1.5, 2.5, 3), " ", $square(9), "\n";
echo greet(greeting: "Namaste", name: "Ravi"), "\n"; // named arguments
echo $withTax(100), " ", implode(",", array_map($square, [1, 2, 3])), "\n";
Output:
15 7 81
Namaste, Ravi!
118 1,4,9
⚠️ Common error: with
strict_types=1, passing"5"to anintparameter throws aTypeError. Convert first:(int) $value.
8. Arrays & Data Structures
PHP arrays are ordered maps — they work as lists, dictionaries, stacks and queues.
<?php
$nums = [5, 3, 8, 1];
$nums[] = 9; // append
sort($nums);
echo implode(" ", $nums), " | count=", count($nums), " | max=", max($nums), "\n";
$user = ["name" => "Neha", "age" => 22, "city" => "Pune"];
$user["email"] = "neha@example.com";
echo $user["name"], " ", array_key_exists("age", $user) ? "has age" : "", " ", in_array("Pune", $user) ? "in Pune" : "", "\n";
echo implode(",", array_keys($user)), "\n";
$evens = array_filter($nums, fn($n) => $n % 2 == 0);
$doubled = array_map(fn($n) => $n * 2, $nums);
$sum = array_reduce($nums, fn($c, $n) => $c + $n, 0);
echo implode(",", $evens), " | ", implode(",", $doubled), " | ", $sum, "\n";
$stack = [];
array_push($stack, 1, 2, 3);
echo array_pop($stack), " ";
$queue = [1, 2, 3];
echo array_shift($queue), "\n";
$students = [["name" => "Ravi", "marks" => 78], ["name" => "Asha", "marks" => 91]];
usort($students, fn($a, $b) => $b["marks"] <=> $a["marks"]);
echo $students[0]["name"], " ", json_encode(array_column($students, "marks")), "\n";
[$a, $b] = [10, 20]; // destructuring
echo "$a $b ", str_repeat("-", 3), " ", ucfirst("php"), " ", strrev("abc"), "\n";
Output:
1 3 5 8 9 | count=5 | max=9
Neha has age in Pune
name,age,city,email
8 | 2,6,10,16,18 | 26
3 1
Asha [91,78]
10 20 --- Php cba
⚠️ Common error:
array_filterkeeps the original keys (e.g.[3 => 8]). Wrap it inarray_values()when you need a clean 0-based list.
9. Object-Oriented Programming
<?php
interface Shape {
public function area(): float;
}
abstract class Base implements Shape {
public function __construct(protected string $name) {} // constructor promotion
public function describe(): string {
return sprintf("%s with area %.2f", $this->name, $this->area());
}
}
class Rectangle extends Base {
public function __construct(private float $w, private float $h) {
parent::__construct("rectangle");
}
public function area(): float { return $this->w * $this->h; }
}
class Circle extends Base {
public function __construct(private float $r) { parent::__construct("circle"); }
public function area(): float { return M_PI * $this->r ** 2; }
}
enum Status: string { // backed enum (PHP 8.1)
case Active = "active";
case Banned = "banned";
public function label(): string { return ucfirst($this->value); }
}
class Counter {
private static int $count = 0;
public static function next(): int { return ++self::$count; }
}
$shapes = [new Rectangle(3, 4), new Circle(1)];
foreach ($shapes as $s) echo $s->describe(), "\n";
echo Status::from("banned")->label(), " ", Counter::next(), Counter::next(), "\n";
Output:
rectangle with area 12.00
circle with area 3.14
Banned 12
Also learn: traits (use LoggerTrait; — reuse code across classes), readonly properties, magic methods (__toString, __get), namespaces and autoloading with Composer (PSR-4).
⚠️ Common error:
Using $this when not in object context— you called a non-static method statically (Class::method()). Create an object first.
10. Advanced Concepts
Forms — the browser sends data in $_GET (URL) or $_POST (body). Always validate and escape it:
<!-- form.php -->
<form method="post">
<input name="email" type="email" required>
<button>Subscribe</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email) {
echo "Subscribed: " . htmlspecialchars($email); // escape output → prevents XSS
} else {
echo "Invalid email";
}
}
?>
Sessions and cookies — keep data across requests:
<?php
session_start(); // must run before any output
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;
setcookie("theme", "dark", time() + 86400 * 30, "/"); // 30 days
echo "Visits this session: " . $_SESSION["visits"];
Databases with PDO — always use prepared statements (prevents SQL injection):
<?php
$pdo = new PDO("mysql:host=localhost;dbname=codify;charset=utf8mb4", "root", "", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$insert = $pdo->prepare("INSERT INTO users (name, email, password) VALUES (:name, :email, :pass)");
$insert->execute([
":name" => $name,
":email" => $email,
":pass" => password_hash($password, PASSWORD_DEFAULT), // never store plain passwords
]);
JSON APIs:
<?php
header("Content-Type: application/json");
$data = json_decode(file_get_contents("php://input"), true); // read JSON body
echo json_encode(["ok" => true, "received" => $data]);
Exceptions:
<?php
function divide(int $a, int $b): float {
if ($b === 0) throw new InvalidArgumentException("Cannot divide by zero");
return $a / $b;
}
try {
echo divide(10, 4), "\n";
echo divide(1, 0), "\n";
} catch (InvalidArgumentException $e) {
echo "Error: ", $e->getMessage(), "\n";
} finally {
echo "done\n";
}
2.5
Error: Cannot divide by zero
done
Composer manages dependencies and autoloading: composer init, composer require guzzlehttp/guzzle, then require 'vendor/autoload.php';. Frameworks: Laravel and Symfony.
11. Examples with Output
Example 1 — Word frequency
<?php
$text = "the cat and the hat and the bat";
$freq = array_count_values(explode(" ", $text));
arsort($freq);
foreach (array_slice($freq, 0, 2, true) as $word => $count) echo "$word: $count\n";
the: 3
and: 2
Example 2 — Palindrome check
<?php
function isPalindrome(string $s): bool {
$clean = strtolower(preg_replace('/[^a-z0-9]/i', '', $s));
return $clean === strrev($clean);
}
var_dump(isPalindrome("A man, a plan, a canal: Panama"), isPalindrome("Codify"));
bool(true)
bool(false)
Example 3 — Build an HTML table from an array
<?php
$rows = [["Asha", 91], ["Ravi", 78]];
echo "<table>\n";
foreach ($rows as [$name, $marks]) {
echo " <tr><td>" . htmlspecialchars($name) . "</td><td>$marks</td></tr>\n";
}
echo "</table>\n";
<table>
<tr><td>Asha</td><td>91</td></tr>
<tr><td>Ravi</td><td>78</td></tr>
</table>
12. Practice Problems
- Print a multiplication table (1–10) for a number from
$_GET['n'], with a default of 5. - Write
isPrime(int $n): booland list all primes below 100. - Build a contact form that validates name, email and message and shows friendly errors.
- Count visits with a session and show a "Welcome back" message using a cookie.
- Create a
userstable and write register/login pages with PDO prepared statements andpassword_hash/password_verify. - Make a JSON API endpoint that returns a list of products filtered by
?category=. - Create a
Cartclass withadd,removeandtotalmethods (with tax). - Solve the logic of Two Sum in PHP using an associative array.
13. Interview Questions
1. == vs === in PHP?
== compares after type juggling; === compares value and type without conversion.
2. include vs require?
Both insert another file. If the file is missing, include gives a warning and continues; require gives a fatal error. _once versions include a file only once.
3. GET vs POST? GET sends data in the URL (bookmarkable, limited size, for reading). POST sends it in the request body (for forms that change data or send passwords).
4. Sessions vs cookies? Cookies are stored in the browser; sessions store data on the server and keep only a session ID in a cookie.
5. How do you prevent SQL injection? Use prepared statements with bound parameters (PDO or MySQLi) — never concatenate user input into SQL.
6. How do you prevent XSS?
Escape output with htmlspecialchars() (and validate input). Never echo raw user input into HTML.
7. What are traits?
A mechanism to reuse methods across unrelated classes (use TraitName;) — PHP has single inheritance, traits fill the gap.
8. What is Composer?
PHP's dependency manager: it installs packages listed in composer.json and generates an autoloader.
9. Abstract class vs interface? Abstract classes can have properties and implemented methods; a class extends one. Interfaces only declare methods (and constants) and a class can implement many.
10. What's new in PHP 8?
JIT compiler, named arguments, union types, match expression, nullsafe operator ?->, constructor property promotion, enums (8.1), readonly properties.
14. Cheat Sheet & References
Basics
// output and variables
echo "Hi $name\n"; printf("%05.2f", $x); print_r($arr); var_dump($x);
$n = (int) "42"; $s = (string) 5; $f = floatval("2.5");
define("MAX", 10); const MIN = 1;
Strings
strlen($s); strtoupper($s); strtolower($s); ucfirst($s); trim($s);
str_contains($s, "a"); str_replace("a", "b", $s); substr($s, 0, 3);
explode(",", $s); implode(",", $arr); strrev($s); sprintf("%d items", $n);
Arrays
$a = [1, 2]; $a[] = 3; count($a); in_array(2, $a); array_search(2, $a);
$m = ["k" => "v"]; array_keys($m); array_values($m); isset($m["k"]);
sort($a); rsort($a); asort($m); ksort($m); usort($a, fn($x, $y) => $x <=> $y);
array_map($f, $a); array_filter($a, $f); array_reduce($a, $f, 0);
array_merge($a, $b); array_slice($a, 1, 2); array_unique($a);
Control flow
if ($a) { } elseif ($b) { } else { }
foreach ($arr as $key => $value) { }
for ($i = 0; $i < 10; $i++) { }
$label = match ($code) { 200 => "ok", 404 => "missing", default => "other" };
Functions and classes
function add(int $a, int $b = 0): int { return $a + $b; }
$sq = fn($x) => $x * $x;
class User { public function __construct(public string $name) {} }
$u = new User("Asha"); echo $u->name;
Web
$_GET["q"]; $_POST["email"]; $_SERVER["REQUEST_METHOD"];
session_start(); $_SESSION["id"] = 1; setcookie("k", "v", time() + 3600);
header("Location: /login.php"); exit;
htmlspecialchars($input); json_encode($data); json_decode($json, true);
password_hash($p, PASSWORD_DEFAULT); password_verify($p, $hash);
PDO
$pdo = new PDO($dsn, $user, $pass);
$st = $pdo->prepare("SELECT * FROM t WHERE id = ?"); $st->execute([$id]);
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
Official documentation