PHP Cheatsheet
PHP powers many websites and APIs. Modern PHP has types, Composer packages, and cleaner object-oriented tools.
Prefer current PHP versions, escape output for HTML, and keep secrets out of the document root.
Full lessons: PHP Tutorials
Basics
Tags and echo
PHP code lives inside <?php ... ?>. Output with echo.
Variables
Names start with $. Loose typing exists; add types where you can.
$name = "Ada";
$count = 3;
Strings
Double quotes interpolate variables; single quotes are literal.
$hi = "Hello, $name";
$raw = 'Hello, $name';
Null coalescing
Provide defaults for missing values.
$user = $_GET["user"] ?? "guest";
php -S
Built-in server for local learning (not production).
php -S localhost:8000
Arrays & control
Arrays
Lists and maps use the same array type.
$nums = [1, 2, 3];
$user = ["name" => "Ada", "id" => 1];
foreach
Iterate values or key/value pairs.
foreach ($user as $key => $value) {
echo "$key=$value\n";
}
if / switch
Branching works like other C-family languages.
if ($count > 0) {
echo "yes";
}
array functions
Helpers like count, in_array, array_map.
count($nums);
in_array(2, $nums, true);
Functions & types
Function
Declare parameters and return types in modern PHP.
function add(int $a, int $b): int {
return $a + $b;
}
Nullable types
Allow null with a leading question mark.
function find(string $id): ?User {
// ...
}
Classes
Properties and methods with visibility keywords.
class User {
public function __construct(public string $name) {}
}
Namespaces
Avoid name clashes; autoload with Composer PSR-4.
namespace App\Models;
class User {}
Web & Composer
Superglobals
$_GET, $_POST, $_SERVER hold request data—validate before use.
$id = (int) ($_GET["id"] ?? 0);
Escape HTML
Prevent XSS when printing user data.
echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");
Composer require
Install libraries and generate the autoloader.
composer require monolog/monolog
require 'vendor/autoload.php';
JSON API peek
Set headers and encode arrays/objects.
header("Content-Type: application/json");
echo json_encode(["ok" => true]);
Comments
One comment per signed-in account. Comments are saved with this page’s URL.