PHP cheat sheet
96 one-line examples for PHP. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
Variables and Types
| Code | What it does |
|---|---|
$name = "Ana"; | A string holds text in quotes. |
$age = 25; | An integer holds a whole number. |
$price = 9.99; | A float holds a decimal number. |
$ok = true; | A boolean holds true or false. |
$list = [1, 2, 3]; | An array holds many values. |
$user = null; | Null means no value is set. |
echo $name; | Print a value to the page. |
var_dump($age); | Show a value and its type. |
$x = (int) "5"; | Cast a string to an integer. |
$total = $a + $b; | Add two numbers together. |
$text = $a . $b; | Join two strings with a dot. |
unset($name); | Remove a variable from memory. |
Strings
| Code | What it does |
|---|---|
$s = 'Hello'; | Single quotes make a plain string. |
$s = "Hi $name"; | Double quotes insert variable values. |
strlen($s); | Count the characters in a string. |
strtoupper($s); | Change all letters to uppercase. |
strtolower($s); | Change all letters to lowercase. |
trim($s); | Remove spaces from both ends. |
str_replace("a", "b", $s); | Replace all matches in a string. |
substr($s, 0, 3); | Take part of a string. |
strpos($s, "lo"); | Find the position of a substring. |
explode(",", $s); | Split a string into an array. |
implode("-", $arr); | Join array items into a string. |
sprintf("%05d", 42); | Format a value into a string. |
Arrays
| Code | What it does |
|---|---|
$a = ["x", "y"]; | Make an indexed array. |
$a[] = "z"; | Add an item to the end. |
$a[0]; | Read the first item. |
count($a); | Count the items in an array. |
$u = ["id" => 1]; | Make an array with named keys. |
$u["id"]; | Read a value by its key. |
array_push($a, "w"); | Add one item to the end. |
array_pop($a); | Remove and return the last item. |
array_keys($u); | Get all the keys of an array. |
array_values($u); | Get all the values of an array. |
in_array("x", $a); | Check if a value exists. |
sort($a); | Sort an array from low to high. |
Control Flow
| Code | What it does |
|---|---|
if ($x > 0) { } | Run code when a test is true. |
if ($x) { } else { } | Run one block or the other. |
elseif ($x == 0) { } | Test another condition in a chain. |
$r = $x ? 1 : 2; | Pick a value with a short test. |
switch ($x) { case 1: } | Compare one value with many cases. |
while ($i < 5) { $i++; } | Repeat while a test stays true. |
for ($i = 0; $i < 5; $i++) { } | Repeat a set number of times. |
foreach ($a as $v) { } | Loop over each array value. |
foreach ($u as $k => $v) { } | Loop over keys and values. |
break; | Stop the loop now. |
continue; | Skip to the next loop step. |
match ($x) { 1 => "a" }; | Return a value from a match. |
Functions
| Code | What it does |
|---|---|
function add($a, $b) { } | Define a function with two parameters. |
return $a + $b; | Send a value back to the caller. |
add(2, 3); | Call a function with arguments. |
function f(int $x): int { } | Set parameter and return types. |
function f($x = 5) { } | Give a parameter a default value. |
function f(...$nums) { } | Accept any number of arguments. |
$f = fn($x) => $x * 2; | Make a short arrow function. |
$f = function ($x) { }; | Make an anonymous function. |
strlen(...); | Use a function as a value. |
function_exists("add"); | Check if a function is defined. |
$g = 'strlen'; $g("hi"); | Call a function by its name. |
static $n = 0; | Keep a value between function calls. |
Forms and Requests
| Code | What it does |
|---|---|
$_GET['id']; | Read a value from the URL. |
$_POST['name']; | Read a value sent by a form. |
isset($_POST['name']); | Check if a form field was sent. |
empty($_POST['name']); | Check if a value is missing or empty. |
htmlspecialchars($s); | Make text safe to print in HTML. |
filter_var($e, FILTER_VALIDATE_EMAIL); | Check that an email is valid. |
$_SERVER['REQUEST_METHOD']; | Read the request method name. |
$_FILES['photo']; | Read an uploaded file. |
$_COOKIE['theme']; | Read a value from a cookie. |
setcookie("theme", "dark"); | Send a cookie to the browser. |
session_start(); | Start or resume a user session. |
$_SESSION['user'] = 1; | Store a value in the session. |
Files and Errors
| Code | What it does |
|---|---|
include 'header.php'; | Load a file and keep going on error. |
require 'config.php'; | Load a file and stop on error. |
file_get_contents($path); | Read a whole file into a string. |
file_put_contents($p, $s); | Write a string to a file. |
fopen($path, 'r'); | Open a file for reading. |
fgets($handle); | Read one line from a file. |
fclose($handle); | Close an open file handle. |
file_exists($path); | Check if a file exists. |
try { } catch (Exception $e) { } | Catch an error and handle it. |
throw new Exception("Bad"); | Raise an error on purpose. |
error_log("Problem"); | Write a message to the error log. |
ini_set('display_errors', '1'); | Turn on error display for debugging. |
Classes and Objects
| Code | What it does |
|---|---|
class User { } | Define a class named User. |
public $name; | A property anyone can read. |
public function getName() { } | A method that belongs to the class. |
$u = new User(); | Create an object from a class. |
$u->name = "Ana"; | Set a property on an object. |
$u->getName(); | Call a method on an object. |
function __construct() { } | Run code when an object is made. |
class Admin extends User { } | Make a child class from a parent. |
parent::__construct(); | Call the parent class constructor. |
interface Run { } | Define a contract for classes. |
class A implements Run { } | Make a class follow an interface. |
$u instanceof User; | Check an object's class type. |