Powers 77% of the web. WordPress, Facebook, and Wikipedia all run on PHP. Server-side scripting made easy.
<?php
// Variables start with $
$name = "Mayank";
$age = 15;
// Print
print "Hello, $name!\n";
echo "Age: $age\n";
// Arrays
$languages = ['Python', 'PHP', 'Go', 'Rust'];
foreach ($languages as $lang) {
echo "I know $lang\n";
}
?>
$var for variables. String, int, float, bool, array, null. PHP is loosely typed.
<?php
$name = "Mayank"; // string
$age = 15; // int
$pi = 3.14159; // float
$passed = true; // bool
$nothing = null; // null
// Type checking
echo gettype($name) . "\n"; // string
settype($age, 'string'); // type juggling
// String functions
echo strlen($name) . "\n"; // 6
echo strtoupper($name) . "\n"; // MAYANK
echo str_replace('a', '@', $name) . "\n";
// Heredoc
$html = <<<HTML
<h1>Hello $name</h1>
<p>Age: $age</p>
HTML;
echo $html;
?>
Arithmetic, string concatenation (.), comparison, logical. PHP uses == for loose, === for strict.
<?php
$a = 10; $b = 3;
echo $a + $b . "\n"; // 13
echo $a / $b . "\n"; // 3.333...
echo $a % $b . "\n"; // 1
// String concatenation
echo "Hello" . " " . "World" . "\n";
// Comparison
echo (10 == "10") ? 'true' : 'false'; // true (loose)
echo (10 === "10") ? 'true' : 'false'; // false (strict)
// Null coalescing (PHP 7+)
$user = $_GET['name'] ?? 'Guest';
echo $user . "\n";
// Spaceship operator (PHP 7+)
echo (1 <=> 2) . "\n"; // -1
echo (2 <=> 2) . "\n"; // 0
echo (3 <=> 2) . "\n"; // 1
?>
<?php
$score = 85;
if ($score >= 90) echo 'A';
elseif ($score >= 80) echo 'B';
else echo 'C';
echo "\n";
// Match expression (PHP 8+)
$day = 3;
echo match($day) {
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
default => 'Other',
} . "\n";
// Foreach
$fruits = ['apple' => 1.5, 'banana' => 0.75, 'cherry' => 2.0];
foreach ($fruits as $name => $price) {
echo "$name: \$$price\n";
}
// Array functions
$nums = [5, 3, 1, 4, 2];
sort($nums);
echo implode(', ', $nums) . "\n";
echo count($nums) . "\n";
echo array_sum($nums) . "\n";
?>
<?php
function add(int $a, int $b): int {
return $a + $b;
}
function greet(string $name, string $prefix = 'Hello'): string {
return "$prefix, $name!";
}
function sum(int ...$nums): int {
return array_sum($nums);
}
// Arrow functions (PHP 7.4+)
$square = fn($x) => $x * $x;
$multiply = fn($a, $b) => $a * $b;
echo add(3, 4) . "\n";
echo greet('Mayank') . "\n";
echo greet('World', 'Hi') . "\n";
echo sum(1, 2, 3, 4, 5) . "\n";
echo $square(5) . "\n";
echo $multiply(3, 4) . "\n";
?>
Indexed arrays, associative arrays, multidimensional. PHP arrays are super flexible.
<?php
// Indexed array
$colors = ['red', 'green', 'blue'];
echo $colors[0] . "\n";
$colors[] = 'yellow'; // append
// Associative array
$person = [
'name' => 'Mayank',
'age' => 15,
'langs' => ['PHP', 'Python', 'Go'],
];
echo $person['name'] . "\n";
// Useful functions
echo count($colors) . "\n";
echo in_array('red', $colors) ? 'yes' : 'no';
echo "\n";
$keys = array_keys($person);
echo implode(', ', $keys) . "\n";
// Map/Filter/Reduce
$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
echo implode(', ', $doubled) . "\n";
$evens = array_filter($nums, fn($n) => $n % 2 == 0);
echo implode(', ', $evens) . "\n";
?>
<?php
// form.html:
// <form method="POST" action="process.php">
// <input name="username" type="text">
// <input name="password" type="password">
// <button>Submit</button>
// </form>
// process.php:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user = htmlspecialchars($_POST['username'] ?? '');
$pass = $_POST['password'] ?? '';
if (empty($user) || empty($pass)) {
echo 'Fill all fields';
} else {
echo "Welcome, $user!";
}
}
// $_GET parameters
$page = $_GET['page'] ?? 1;
per_page = $_GET['per_page'] ?? 10;
echo "Page $page, showing $per_page per page\n";
// $_SERVER info
echo 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
echo 'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'] . "\n";
?>
<?php
// Simple read/write
file_put_contents('test.txt', 'Hello PHP!\n');
echo file_get_contents('test.txt');
// Read line by line
$lines = file('test.txt', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) echo $line . "\n";
// Append
file_put_contents('log.txt', date('c') . ' - event\n', FILE_APPEND);
// File functions
echo file_exists('test.txt') ? 'exists' : 'missing';
echo "\n";
echo filesize('test.txt') . " bytes\n";
// Read CSV
$csv = "name,age\nMayank,15\nAlice,20\n";
file_put_contents('data.csv', $csv);
$rows = array_map('str_getcsv', file('data.csv'));
array_shift($rows); // remove header
foreach ($rows as $row) echo "$row[0]: $row[1]\n";
?>
<?php
// Encode
$data = ['name' => 'Mayank', 'age' => 15, 'langs' => ['PHP', 'Go']];
$json = json_encode($data);
echo $json . "\n";
// Decode
$decoded = json_decode($json, true); // true = associative array
echo $decoded['name'] . "\n";
// API endpoint example (api.php)
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
echo json_encode(['users' => [
['id' => 1, 'name' => 'Mayank'],
['id' => 2, 'name' => 'Alice'],
]]);
} elseif ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
echo json_encode(['status' => 'created', 'data' => $input]);
}
?>
<?php
interface Loggable { public function log(): string; }
abstract class Entity {
protected int $id;
public function __construct(int $id) { $this->id = $id; }
abstract public function type(): string;
}
class User extends Entity implements Loggable {
public function __construct(int $id, public string $name, public string $email) {
parent::__construct($id);
}
public function type(): string { return 'User'; }
public function log(): string { return "User {$this->name} ({$this->email})"; }
}
$user = new User(1, 'Mayank', 'mayank@test.com');
echo $user->log() . "\n";
echo $user->type() . "\n";
?>
Traits share code between classes. Namespaces organize code and prevent name clashes.
<?php
namespace App\Models;
trait HasTimestamps {
public ?string $created_at = null;
public function setTimestamp(): void { $this->created_at = date('c'); }
}
class Post {
use HasTimestamps;
public function __construct(public string $title, public string $body) {}
}
$post = new Post('Hello', 'World');
$post->setTimestamp();
echo $post->title . " at " . $post->created_at . "\n";
// Autoloading with Composer (composer.json)
// {
// "autoload": { "psr-4": { "App\\": "src/" } }
// }
// require 'vendor/autoload.php';
?>
<?php
class InsufficientFundsException extends RuntimeException {
public function __construct(float $balance, float $amount) {
parent::__construct("Need \$amount but only have \$balance");
}
}
class BankAccount {
public function __construct(private float $balance = 0) {}
public function withdraw(float $amount): float {
if ($amount > $this->balance) throw new InsufficientFundsException($this->balance, $amount);
$this->balance -= $amount;
return $this->balance;
}
public function getBalance(): float { return $this->balance; }
}
try {
$acc = new BankAccount(100);
echo $acc->withdraw(30) . "\n";
echo $acc->withdraw(80) . "\n";
} catch (InsufficientFundsException $e) {
echo "Error: " . $e->getMessage() . "\n";
} finally {
echo "Transaction complete\n";
}
?>
PDO connects to MySQL, PostgreSQL, SQLite. Prepared statements prevent SQL injection.
<?php
// Connect to SQLite (works without a server)
$pdo = new PDO('sqlite:test.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Create table
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)");
// Insert with prepared statement
$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
$stmt->execute(['Mayank', 'mayank@test.com']);
echo "Inserted user ID: " . $pdo->lastInsertId() . "\n";
// Query
$stmt = $pdo->query('SELECT * FROM users');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "{$row['name']} ({$row['email']})\n";
}
// Named parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
$stmt->execute([':name' => 'Mayank']);
$user = $stmt->fetch();
echo $user['email'] . "\n";
?>