Code library
Free snippets & functions
Copy, adapt and use them in your own projects.
$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.
<div class="table-responsive">
<table class="table table-striped table-hover align-middle">
<thead>
<tr><th>#</th><th>Name</th><th>Email</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>Ali</td><td>ali@example.com</td></tr>
</tbody>
</table>
</div>Wrap the table so it scrolls sideways on small screens instead of breaking the layout.
<div class="container py-4">
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
<div class="col">
<div class="card h-100">
<img src="photo.jpg" class="card-img-top" alt="">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Short description.</p>
<a href="#" class="btn btn-primary">Open</a>
</div>
</div>
</div>
<!-- repeat .col -->
</div>
</div>One column on phones, two on tablets, three on desktops.
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#nav" aria-label="Menu">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="nav">
<ul class="navbar-nav ms-auto">
<li class="nav-item"><a class="nav-link active" href="#">Home</a></li>
<li class="nav-item"><a class="nav-link" href="#">About</a></li>
<li class="nav-item"><a class="nav-link" href="#">Services</a></li>
</ul>
</div>
</div>
</nav>Collapses into a menu button on small screens.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page title</title>
<meta name="description" content="A short description for search engines.">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>…</header>
<main>…</main>
<footer>…</footer>
<script src="app.js"></script>
</body>
</html>The minimum every modern page needs, including the viewport tag.
const money = new Intl.NumberFormat('en-PK', { style: 'currency', currency: 'PKR' });
console.log(money.format(1250000)); // PKR 1,250,000.00
console.log(new Intl.NumberFormat().format(1234567.891)); // 1,234,567.891Intl.NumberFormat handles separators and currency for you.
const root = document.documentElement;
try { root.dataset.theme = localStorage.getItem('theme') || ''; } catch (e) {}
document.querySelector('#theme').addEventListener('click', () => {
const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
root.dataset.theme = next;
try { localStorage.setItem('theme', next); } catch (e) {}
});Remember the visitor’s choice in localStorage.
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (e) {
return false;
}
}
copyText('Hello').then(ok => console.log(ok ? 'Copied' : 'Failed'));Uses the Clipboard API. It needs HTTPS or localhost.
$('a[href^="#"]').on('click', function (e) {
var target = $(this.getAttribute('href'));
if (!target.length) return;
e.preventDefault();
$('html, body').animate({ scrollTop: target.offset().top - 80 }, 500);
});Animate the page to an anchor when a link is clicked.
$('#toggle').on('click', function () {
var $pw = $('#password');
var show = $pw.attr('type') === 'password';
$pw.attr('type', show ? 'text' : 'password');
$(this).text(show ? 'Hide' : 'Show');
});Switch the input type between password and text.
$.ajax({
url: 'save.php',
method: 'POST',
dataType: 'json',
data: { name: $('#name').val(), email: $('#email').val() }
})
.done(function (res) {
alert(res.message);
})
.fail(function (xhr) {
alert('Error: ' + xhr.status);
});Post data and handle success and failure.
async function loadUsers() {
try {
const res = await fetch('api/users.php');
if (!res.ok) throw new Error('HTTP ' + res.status);
const users = await res.json();
console.log(users);
} catch (err) {
console.error('Could not load users:', err);
}
}
loadUsers();The modern way to do AJAX. Check response.ok before using the data.
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().