All Cheat Sheets
php
PHP Cheat Sheet
Basics
PHP tagsEmbed PHP in HTML<?php
echo "Hello, World!";
?>Variables$ prefix, no type declaration$name = "Mishu";
$age = 25;
$price = 19.99;CommentsSingle and multi-line// Single line
# Also single line
/* Multi-line */Echo / PrintOutput to browserecho "Hello $name!";
print("Hello World");Control Flow
If-elseConditional executionif ($x > 0) {
echo "positive";
} else {
echo "not positive";
}ForeachIterate arrays$items = ["a", "b", "c"];
foreach ($items as $item) {
echo $item;
}
foreach ($arr as $key => $value) { }For loopIterationfor ($i = 0; $i < 10; $i++) {
echo $i;
}Arrays & Functions
ArrayIndexed and associative arrays$nums = [1, 2, 3];
$user = [
"name" => "Mishu",
"age" => 25
];
echo $user["name"];FunctionFunction definitionfunction greet($name, $greeting = "Hello") {
return "$greeting, $name!";
}
echo greet("Mishu");Array functionsUseful built-in functionscount($arr);
array_push($arr, $value);
array_merge($arr1, $arr2);
in_array($value, $arr);Forms & Sessions
GET / POSTAccess form data// form.html: <input name="email">
$email = $_POST['email'];
$name = $_GET['name'];SessionPersist data across pagessession_start();
$_SESSION['user_id'] = 1;
// On next page:
session_start();
$id = $_SESSION['user_id'];MySQL connectionConnect to database$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) { }