Code library
Free snippets & functions
Copy, adapt and use them in your own projects.
function group_by(array $rows, string $key): array
{
$out = [];
foreach ($rows as $row) {
$out[$row[$key]][] = $row;
}
return $out;
}
$products = [
['name' => 'Pen', 'cat' => 'Office'],
['name' => 'Laptop', 'cat' => 'Tech'],
['name' => 'Paper', 'cat' => 'Office'],
];
print_r(group_by($products, 'cat')); // Office => [Pen, Paper], Tech => [Laptop]Turn a flat list of database rows into groups (for example products by category).
function flash(?string $msg = null): ?string
{
if ($msg !== null) { $_SESSION['flash'] = $msg; return null; }
$m = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']);
return $m;
}
// After saving:
flash('Saved successfully.');
header('Location: /list.php');
exit;
// On the next page:
if ($m = flash()) echo '<p class="notice">' . htmlspecialchars($m, ENT_QUOTES, 'UTF-8') . '</p>';Store a message in the session before a redirect and show it once on the next page.
function redirect(string $to): never
{
header('Location: ' . $to, true, 303); // 303 = "see other": the browser switches to GET
exit;
}
// Only allow redirects to pages on your own site
function safe_next(string $next, string $fallback = '/'): string
{
return (preg_match('#^/(?!/)[A-Za-z0-9/_\-.?=&]*$#', $next)) ? $next : $fallback;
}
redirect(safe_next($_GET['next'] ?? '/'));Always call exit after a redirect, and never redirect to an address taken straight from the URL (open redirect).
$name = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$age = filter_var($_POST['age'] ?? '', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 120]]);
$errors = [];
if ($name === '' || mb_strlen($name) > 80) $errors[] = 'Enter a name up to 80 characters.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Enter a valid email address.';
if ($age === false) $errors[] = 'Age must be a number from 1 to 120.';
if (!$errors) {
// safe to use $name, $email, $age (still use prepared statements for the database)
}Trim, check and normalise values from a form before using them. Validation rules belong on the server; the browser checks are only a convenience.
$s = sprintf('%s has %d items, total %.2f', 'Cart', 3, 59.5); // Cart has 3 items, total 59.50
$id = sprintf('INV-%05d', 42); // INV-00042
$pct = sprintf('%d%%', 80); // 80%
$col = sprintf('#%02x%02x%02x', 255, 128, 0); // #ff8000
printf("%-10s|%6.1f\n", 'Left', 3.14159); // padded columnssprintf() puts values into a template and returns the string. printf() prints it.
const SITE_NAME = 'My Site'; // top level
define('MAX_UPLOAD_MB', 5); // also works inside if-blocks
class Role
{
public const ADMIN = 'admin';
public const EDITOR = 'editor';
}
echo SITE_NAME, ' ', MAX_UPLOAD_MB, ' ', Role::ADMIN;
var_dump(defined('SITE_NAME')); // trueConstants never change after they are set. Use them for fixed settings and magic numbers.
function divide(int $a, int $b): float
{
if ($b === 0) {
throw new InvalidArgumentException('Cannot divide by zero');
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (InvalidArgumentException $e) {
echo 'Problem: ' . $e->getMessage();
} catch (Throwable $e) {
error_log($e->getMessage()); // anything else: log it, show a generic message
echo 'Something went wrong.';
} finally {
// runs always (close files, release locks)
}Wrap risky code in try. Catch the specific exception you expect and always have a safe fallback.
$a = 0; $b = ''; $c = null;
var_dump(isset($a)); // true (exists)
var_dump(isset($c)); // false (null)
var_dump(empty($a)); // true (0 is empty)
var_dump(empty($b)); // true
var_dump(is_null($c)); // true
$page = $_GET['page'] ?? 1; // default when missing or null
$name ??= 'Guest'; // assign only if missing/null (PHP 7.4+)Know the difference: isset checks that a value exists and is not null. empty treats 0, "" and "0" as empty.
$dice = random_int(1, 6); // secure random number
$token = bin2hex(random_bytes(16)); // 32 hex characters
$code = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT); // 6-digit code
$items = ['a', 'b', 'c'];
$pick = $items[array_rand($items)]; // one random item
shuffle($items); // random orderUse random_int() and random_bytes() for anything security related. rand() and mt_rand() are not safe for that.
$n = 1234567.891;
echo number_format($n); // 1,234,568
echo number_format($n, 2); // 1,234,567.89
echo number_format($n, 2, ',', '.'); // 1.234.567,89
echo round(3.14159, 2); // 3.14
echo floor(4.9); // 4
echo ceil(4.1); // 5
echo intdiv(17, 5), ' ', 17 % 5; // 3 2number_format() adds separators. round(), floor() and ceil() change the value itself.
$name = 'Ali';
echo <<<HTML
<h1>Hello, {$name}</h1>
<p>Today is {$_SERVER['REQUEST_METHOD']}.</p>
HTML;
echo <<<'RAW'
This is printed as is: $name and {$name}
RAW;Heredoc expands variables like double quotes. Nowdoc keeps everything literally, like single quotes.
$rows = [
['id' => 1, 'name' => 'Ali', 'active' => true],
['id' => 2, 'name' => 'Sara', 'active' => false],
['id' => 3, 'name' => 'Omar', 'active' => true],
];
$names = array_column($rows, 'name'); // ['Ali','Sara','Omar']
$byId = array_column($rows, 'name', 'id'); // [1=>'Ali', 2=>'Sara', ...]
$active = array_filter($rows, fn($r) => $r['active']); // keeps keys
$upper = array_map('strtoupper', $names); // ['ALI','SARA','OMAR']
$total = array_sum(array_column($rows, 'id')); // 6Transform, filter and pick columns without writing a loop.
$nums = [5, 3, 9, 1];
sort($nums); // [1,3,5,9]
rsort($nums); // [9,5,3,1]
$ages = ['Sara' => 25, 'Ali' => 30, 'Omar' => 20];
asort($ages); // by value, keeps keys
ksort($ages); // by key
$people = [['n' => 'Ali', 'a' => 30], ['n' => 'Sara', 'a' => 25]];
usort($people, fn($x, $y) => $x['a'] <=> $y['a']); // youngest firstsort() for values, ksort() for keys, usort() with your own comparison.
$file = __DIR__ . '/notes.txt';
file_put_contents($file, "first line\n", LOCK_EX); // replace
file_put_contents($file, "second line\n", FILE_APPEND | LOCK_EX); // add
if (is_file($file)) {
$text = file_get_contents($file);
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}file_put_contents and file_get_contents handle most jobs. LOCK_EX avoids two writers clashing.
setcookie('theme', 'dark', [
'expires' => time() + 60 * 60 * 24 * 30, // 30 days
'path' => '/',
'secure' => true, // HTTPS only
'httponly' => true, // not readable by JavaScript
'samesite' => 'Lax',
]);
$theme = $_COOKIE['theme'] ?? 'light';Cookies are sent with the next request. Set HttpOnly and SameSite so scripts cannot read them.
echo date('Y-m-d H:i:s'); // 2026-11-03 14:30:00
echo date('d M Y', strtotime('2026-11-03')); // 03 Nov 2026
$d = new DateTime('2026-11-03 14:30');
echo $d->format('l, jS F Y'); // Tuesday, 3rd November 2026
$d->modify('+7 days');
echo $d->format('Y-m-d'); // 2026-11-10date() formats a timestamp. DateTime is better for anything beyond a simple format.
$id = (int)($_GET['id'] ?? 0); // number from the URL
$q = trim((string)($_GET['q'] ?? '')); // search text
$name = trim((string)($_POST['name'] ?? ''));
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $name !== '') {
// handle the form
}Use ?? so a missing key does not raise a warning. Always treat input as text from a stranger.
// config.php returns an array: <?php return ['site' => 'My site'];
$config = require __DIR__ . '/config.php';
require_once __DIR__ . '/includes/functions.php'; // loaded only once
include __DIR__ . '/header.php'; // warning if missing, page continuesUse require_once for files the page cannot work without. __DIR__ keeps the path correct from anywhere.
function price(float $amount, float $taxRate = 0.17, string $currency = 'PKR'): string
{
$total = $amount * (1 + $taxRate);
return number_format($total, 2) . ' ' . $currency;
}
echo price(1000); // 1,170.00 PKR
echo price(1000, currency: 'USD'); // named argument (PHP 8+)
echo price(1000, 0); // 1,000.00 PKRType the arguments and the return value. Optional arguments get a default.
function statusLabel(int $code): string
{
return match (true) {
$code >= 500 => 'Server error',
$code >= 400 => 'Client error',
$code >= 300 => 'Redirect',
$code >= 200 => 'OK',
default => 'Unknown',
};
}
$role = 'editor';
echo match ($role) {
'admin', 'owner' => 'Full access',
'editor' => 'Can edit',
default => 'Read only',
};match returns a value, compares strictly and throws if nothing matches (PHP 8+).
$colors = ['red', 'green'];
$colors[] = 'blue'; // add to the end
$user = ['name' => 'Ali', 'city' => 'Lahore'];
$user['age'] = 30; // add a key
foreach ($colors as $i => $color) {
echo "$i: $color\n";
}
foreach ($user as $key => $value) {
echo "$key = $value\n";
}
echo count($colors); // 3
var_dump(in_array('green', $colors)); // true
var_dump(array_key_exists('city', $user)); // trueIndexed and associative arrays, adding items and looping with foreach.
$s = ' Hello PHP World ';
$t = trim($s); // 'Hello PHP World'
echo strlen($t); // 15
echo strtoupper($t), strtolower($t);
echo substr($t, 0, 5); // 'Hello'
echo str_replace('PHP', 'Web', $t); // 'Hello Web World'
var_dump(str_contains($t, 'PHP')); // true (PHP 8+)
var_dump(str_starts_with($t, 'Hello')); // true (PHP 8+)
print_r(explode(' ', $t)); // ['Hello','PHP','World']
echo implode('-', ['a', 'b', 'c']); // 'a-b-c'The functions you will use all the time: length, case, search, cut and clean.
$name = 'Ali'; // string
$age = 30; // int
$price = 19.99; // float
$ok = true; // bool
$list = [1, 2, 3]; // array
$none = null; // null
echo gettype($name), ' ', gettype($age), ' ', gettype($price), ' ', gettype($list);PHP variables start with $. Use gettype() or var_dump() to see the type.
function time_ago(string $datetime): string
{
$diff = time() - strtotime($datetime);
if ($diff < 60) return 'just now';
if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
if ($diff < 604800) return floor($diff / 86400) . ' days ago';
return date('M j, Y', strtotime($datetime));
}Turn a date into friendly text.
function slugify(string $text): string
{
$text = strtolower(trim($text));
$text = preg_replace('/[^a-z0-9]+/', '-', $text);
return trim($text, '-') ?: 'item';
}
echo slugify('My First Post!'); // my-first-postTurns "My First Post!" into "my-first-post".
function json_out(array $data, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
json_out(['ok' => true, 'message' => 'Saved']);A tiny helper for AJAX endpoints. Sends the right header and stops.
function h($value): string
{
return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}
echo '<p>Hello, ' . h($_GET['name'] ?? 'guest') . '</p>';Always escape user data before printing it into HTML.
$dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);A safe connection: exceptions on errors, real prepared statements and utf8mb4.
$st = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$st->execute([$email]);
$user = $st->fetch(PDO::FETCH_ASSOC);A prepared statement keeps user input out of the SQL text.
$hash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($input, $hash)) {
// logged in
}Store only the hash. Verify at login with password_verify().