320 x 50 Mobile Ad
Cheat Sheets

PHP Cheat Sheet

Transform, format, and optimize your data instantly with this free client-side tool.

Basics

<?php ... ?>

PHP tags

echo 'text';

Output a string

print('text');

Output a string (returns 1)

$var = 'value';

Variable declaration

define('CONST', 'val');

Define a constant

isset($var)

Determine if a variable is declared and is different than null

empty($var)

Determine whether a variable is empty

unset($var)

Unset a given variable

Control Structures

if ($x > 5) { ... }

If statement

elseif ($x == 5) { ... }

Else if statement

for ($i = 0; $i < 5; $i++)

For loop

foreach ($arr as $item)

Foreach loop (values only)

foreach ($arr as $k => $v)

Foreach loop (keys and values)

while ($x > 0) { ... }

While loop

switch ($var) { case 1: ... }

Switch statement

match ($var) { 1 => ... }

Match expression (PHP 8.0+)

Strings

strlen($str)

Get string length

strpos($str, 'find')

Find the position of the first occurrence of a substring

str_replace('a', 'b', $s)

Replace all occurrences of the search string with the replacement

strtolower($str)

Make a string lowercase

strtoupper($str)

Make a string uppercase

substr($str, 0, 5)

Return part of a string

explode(',', $str)

Split a string by string

implode('-', $arr)

Join array elements with a string

trim($str)

Strip whitespace from the beginning and end of a string

Arrays

$arr = [1, 2, 3];

Array declaration (short syntax)

$arr = ['a' => 1, 'b' => 2];

Associative array declaration

count($arr)

Count all elements in an array

array_push($arr, $val);

Push one or more elements onto the end of array

array_pop($arr);

Pop the element off the end of array

array_shift($arr);

Shift an element off the beginning of array

array_unshift($arr, $val);

Prepend one or more elements to the beginning of an array

array_key_exists('k', $arr)

Checks if the given key or index exists in the array

in_array($val, $arr)

Checks if a value exists in an array

array_merge($a1, $a2)

Merge one or more arrays

sort($arr)

Sort array in ascending order

array_map($callback, $arr)

Applies the callback to the elements of the given arrays

array_filter($arr)

Filters elements of an array using a callback function

Functions

function myFunc($arg) { ... }

Function definition

function f($arg = 'default')

Function with default arguments

function f(string $arg): int

Function with type hinting and return type

fn($x) => $x * 2;

Arrow function definition

func_get_args()

Returns an array comprising a function's argument list

Object Oriented

class MyClass { ... }

Class definition

public $property;

Public property declaration

public function __construct()

Class constructor magic method

$obj = new MyClass();

Instantiate a class

$obj->property

Access object property

self::$property

Access static property from within the class

parent::__construct()

Call parent class constructor

interface MyInterface { ... }

Interface definition

trait MyTrait { ... }

Trait definition

class A extends B implements C

Class inheritance and interface implementation

Superglobals

$_GET['param']

Variables passed to the current script via the URL parameters

$_POST['param']

Variables passed to the current script via the HTTP POST method

$_SERVER['REMOTE_ADDR']

IP address of the client

$_SESSION['user']

Session variables

$_COOKIE['user']

HTTP Cookies

session_start();

Start new or resume existing session

setcookie('name', 'val')

Send a cookie

File Handling

$file = fopen('f.txt', 'r');

Opens file or URL

fread($file, filesize('f'));

Binary-safe file read

fwrite($file, 'text');

Binary-safe file write

fclose($file);

Closes an open file pointer

file_get_contents('f.txt')

Reads entire file into a string

file_put_contents('f.txt', $data)

Write data to a file

file_exists('file.txt')

Checks whether a file or directory exists

Error Handling

try { ... }

Start try block

catch (Exception $e) { ... }

Catch generic exception

finally { ... }

Block always executed after try/except

throw new Exception('msg');

Throw an exception manually

error_reporting(E_ALL);

Sets which PHP errors are reported

Includes

include 'file.php';

Include and evaluate the specified file

require 'file.php';

Include file, fatal error if not found

include_once 'file.php';

Include file only once

require_once 'file.php';

Require file only once

Advanced

array_map(fn($n) => $n * 2, $arr)

Arrow function mapping over an array

error_reporting(E_ALL); ini_set('display_errors', 1);

Enable strict error reporting for debugging

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Set PDO to throw exceptions on SQL errors

320 x 50 Mobile Ad

Frequently Asked Questions

Got questions? We've got answers.

The Php Cheatsheet is a quick-reference guide that provides developers with the most essential and frequently used Php commands, syntax, and snippets in one centralized place.
This reference is built for both beginners who are just learning Php and need a quick syntax lookup, as well as seasoned professionals who need to jog their memory on complex commands.
You can use the real-time search bar at the top of the cheatsheet. Simply type a keyword (like &#39;delete&#39; or &#39;file&#39;) and the list will instantly filter to show only matching Php commands.
Yes! Every command block features a one-click copy button. Just hover over the command and click the copy icon to instantly send the snippet to your clipboard.
The cheatsheet is divided into logical categories such as Basics, Network, Operations, and specific Php features. You can click on the category filters at the top to isolate specific groups of commands.
Absolutely. This Php reference guide is 100% free, requiring no sign-ups or subscriptions, and is always available when you need it.
While these are standard Php operations, you should always understand what a command does before running it, especially if it involves system operations or destructive actions.
Yes, we have recently expanded this cheatsheet to include advanced snippets, best practices, and edge-case syntax that go beyond basic introductory commands.
ADVERTISEMENT
Boost Your Business Online