AI Generate PHP docs instantly

PHP Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with PHP basics

Hello World

<?php
echo "Hello, World!";

Comments

// Single line comment
# Also single line
/* Multi-line
   comment */

Variables

$name = "John";  // No type declaration
$age = 25;       // Dynamically typed

Type Casting

(int) "42"      // string to int
(string) 42     // int to string
(float) "3.14"  // to float

Check Type

gettype($var)   // "string", "integer"
is_string($var) // true/false
is_array($var)  // true/false

Variables & Data Types

8 snippets

Store and manage data in PHP

String

$name = "John";

Integer

$age = 25;

Float

$price = 19.99;

Boolean

$isActive = true;

Array

$fruits = ["apple", "banana", "cherry"];

Associative Array

$person = ["name" => "John", "age" => 30];

Null

$value = null;

Constant

const PI = 3.14159;
define("MAX", 100);

Operators

7 snippets

Symbols for calculations and comparisons

Arithmetic

+ - * /    // Add, Sub, Mul, Div
%          // Modulus
**         // Exponent
++ --      // Increment/Decrement

Comparison

==   !=    // Equal (loose)
===  !==   // Equal (strict)
>    <     // Greater, Less
>=   <=    // Greater/Less or equal
<=>        // Spaceship (returns -1, 0, 1)

Logical

&&  and    // AND
||  or     // OR
!   // NOT
xor        // XOR

String

.    // Concatenation
.=   // Concatenate and assign
"Hello, $name"  // Interpolation

Null Operators

??   // Null coalescing
??=  // Null coalescing assignment
?->  // Nullsafe operator

Assignment

=   +=  -=  *=  /=  %=
.=  // String concatenate assign
??= // Null coalescing assign

Bitwise

&   // AND
|   // OR
^   // XOR
~   // NOT
<<  // Left shift
>>  // Right shift

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

9 snippets

Repeat code efficiently with iterations

For

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

Foreach (Array)

foreach ($fruits as $fruit) {
    echo $fruit;
}

Foreach (Key-Value)

foreach ($person as $key => $value) {
    echo "$key: $value";
}

While

while ($count < 10) {
    $count++;
}

Do While

do {
    $count++;
} while ($count < 10);

Break

for ($i = 0; $i < 10; $i++) {
    if ($i === 5) break;
}

Continue

for ($i = 0; $i < 10; $i++) {
    if ($i === 5) continue;
    echo $i;
}

Break Level

foreach ($outer as $o) {
    foreach ($inner as $i) {
        if ($i === 5) break 2; // Breaks both
    }
}

Array Functions

array_map(fn($n) => $n * 2, $nums);
array_filter($nums, fn($n) => $n > 0);

Conditionals

5 snippets

Direct program execution with conditions

If/Else

if ($x > 0) {
    echo "positive";
} elseif ($x < 0) {
    echo "negative";
} else {
    echo "zero";
}

Ternary

$result = $condition ? "yes" : "no";

Null Coalescing

$name = $user ?? "Guest";
$name = $user['name'] ?? "Unknown";

Match

$result = match($day) {
    "Mon" => "Monday",
    "Tue", "Wed" => "Midweek",
    default => "Other"
};

Switch

switch ($day) {
    case "Mon":
        echo "Monday";
        break;
    default:
        echo "Other";
}

Functions

5 snippets

Reusable blocks of code

Function

function greet(string $name): string {
    return "Hello, $name!";
}

Default Param

function greet(string $name = "World"): string {
    return "Hello, $name!";
}

Arrow Function

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

Variadic

function sum(...$nums): int {
    return array_sum($nums);
}

Named Args

greet(name: "John", age: 30);

Array Functions

6 snippets

Manipulate and transform arrays

Map

$doubled = array_map(fn($n) => $n * 2, $nums);

Filter

$evens = array_filter($nums, fn($n) => $n % 2 === 0);

Reduce

$sum = array_reduce($nums, fn($a, $b) => $a + $b, 0);

Merge

$all = array_merge($arr1, $arr2);

Sort

sort($nums);
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);

Search

$key = array_search("apple", $fruits);

Classes & OOP

4 snippets

Class

class Dog {
    public function __construct(
        public string $name
    ) {}

    public function bark(): string {
        return "{$this->name} says woof!";
    }
}

Inheritance

class Puppy extends Dog {
    public function play(): string {
        return "{$this->name} is playing!";
    }
}

Interface

interface Animal {
    public function speak(): string;
}

Trait

trait Loggable {
    public function log(string $msg): void {
        echo $msg;
    }
}

Error Handling

4 snippets

Try/Catch

try {
    $result = riskyOperation();
} catch (Exception $e) {
    echo $e->getMessage();
}

Finally

try {
    // code
} catch (Exception $e) {
    // handle
} finally {
    cleanup();
}

Throw

throw new InvalidArgumentException("Invalid input");

Custom Exception

class MyException extends Exception {}

String Operations

7 snippets

Interpolation

$greeting = "Hello, $name!";

Concatenate

$full = $first . " " . $last;

Length

strlen($str);

Substring

substr($str, 0, 5);

Replace

str_replace("old", "new", $str);

Split

explode(",", "a,b,c");

Join

implode(",", ["a", "b", "c"]);

More Cheat Sheets

FAQ

Frequently asked questions

What is a PHP cheat sheet?

A PHP cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in PHP. It helps developers quickly look up syntax without searching through documentation.

How do I learn PHP quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important PHP concepts?

Key PHP concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my PHP code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your PHP code using AI.

Code Conversion Tools

Convert PHP to Other Languages

Easily translate your PHP code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate PHP Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week