PHP Cheat Sheet

Syntax and Tags ()

PHP code is written inside special tags:

<?php
  echo "Hello, World!";
?>

Variables and Constants

$name = "John";
const PI = 3.14;
define("SITE_NAME", "MySite");

Data Types

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • NULL
$str = "Hello";
$int = 5;
$flt = 3.14;
$bool = true;
$arr = [1, 2, 3];
$obj = new stdClass();
$none = null;

Operators

Arithmetic

+, -, *, /, %

Comparison

==, !=, ===, !==, <, >, <=, >=

Logical

&&, ||, !

Assignment

=, +=, -=, *=, /=

Type Casting

$num = (int)"123";
$float = (float)"12.34";
$bool = (bool)1;

Control Flow

if / else / elseif

if ($x > 0) {
  echo "Positive";
} elseif ($x < 0) {
  echo "Negative";
} else {
  echo "Zero";
}

switch

switch ($color) {
  case "red":
    echo "Red";
    break;
  default:
    echo "Other";
}

Loops

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

foreach ($arr as $value) {
  echo $value;
}

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

do {
  $x--;
} while ($x > 0);

break / continue

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

Functions

Function Declaration

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

Default Parameters

function greet($name = "Guest") {
  echo "Hello, $name";
}

Variable-length Arguments (...$args)

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

Return Values

function add($a, $b) {
  return $a + $b;
}

Anonymous Functions (Closures)

$greet = function($name) {
  return "Hello $name";
};
echo $greet("Sam");

Arrow Functions (fn)

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

Arrays

Indexed and Associative Arrays

$colors = ["red", "green"];
$ages = ["Peter" => 35, "Ben" => 37];

Array Functions

count($arr);
array_merge($a, $b);
array_map(fn($x) => $x * 2, $arr);

Looping through Arrays

foreach ($arr as $value) {
  echo $value;
}

Superglobals

$_GET['id'];
$_POST['name'];
$_SERVER['REQUEST_METHOD'];

Strings

String Concatenation

$greeting = "Hello" . " World";

String Functions

strlen("hello");
strpos("hello", "e");
str_replace("world", "PHP", "hello world");

Heredoc and Nowdoc

$text = <<<EOD
Line 1
Line 2
EOD;

$raw = <<<'EOD'
Raw string
EOD;

Object-Oriented Programming

Classes and Objects

class Person {
  public $name;
  function __construct($name) {
    $this->name = $name;
  }
  function greet() {
    return "Hello, $this->name";
  }
}
$john = new Person("John");
echo $john->greet();

Properties and Methods

Defined using public, private, or protected.

Constructors / Destructors

function __destruct() {
  echo "Goodbye!";
}

Inheritance

class Animal {
  function speak() {
    echo "Sound";
  }
}
class Dog extends Animal {
  function speak() {
    echo "Bark";
  }
}

Static Members

class Math {
  public static function add($a, $b) {
    return $a + $b;
  }
}
echo Math::add(2, 3);

Interfaces / Traits

interface Logger {
  public function log($msg);
}

trait Shared {
  public function sayHi() {
    echo "Hi";
  }
}

Namespaces

namespace AppControllers;
use AppModelsUser;

File Handling

Reading / Writing Files

$file = fopen("data.txt", "r");
echo fread($file, filesize("data.txt"));
fclose($file);

file_put_contents("log.txt", "Hello");
echo file_get_contents("log.txt");

File Uploads

move_uploaded_file($_FILES['file']['tmp_name'], "uploads/" . $_FILES['file']['name']);

File System Functions

mkdir("newdir");
unlink("file.txt");
rename("old.txt", "new.txt");

Error Handling

Error Types

Notices, Warnings, Fatal errors, Parse errors

try / catch / finally

try {
  throw new Exception("Error!");
} catch (Exception $e) {
  echo $e->getMessage();
} finally {
  echo "Done";
}

Custom Exceptions

class MyException extends Exception {}
throw new MyException("Custom error");

Error Reporting

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

Forms and User Input

GET vs POST

$name = $_GET['name'];
$email = $_POST['email'];

Form Validation

if (empty($_POST['email'])) {
  echo "Email is required";
}

Sanitization

$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
echo htmlspecialchars($email);

Sessions and Cookies

Starting Session

session_start();

Setting / Getting Session Variables

$_SESSION['user'] = "admin";
echo $_SESSION['user'];

Setting / Reading Cookies

setcookie("user", "John", time() + 3600);
echo $_COOKIE['user'];

MySQLi / PDO

Connecting to Database (MySQLi)

$conn = new mysqli("localhost", "root", "", "test");

Executing Queries

$result = $conn->query("SELECT * FROM users");

Prepared Statements

$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

Fetching Results

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
  echo $row['name'];
}

Useful Built-in Functions

Date and Time

echo date("Y-m-d H:i:s");
echo strtotime("next Friday");

JSON Handling

$json = json_encode(["name" => "John"]);
$data = json_decode($json, true);

Regular Expressions

preg_match("/php/", "I love php");
preg_replace("/php/", "PHP", "php is cool");

Include / Require

include "header.php";
require "config.php";

Modern PHP

Type Declarations

function add(int $a, int $b): int {
  return $a + $b;
}

Null Coalescing Operator (??)

$name = $_GET['name'] ?? 'Guest';

Spaceship Operator (<=>)

echo 5 <=> 10; // -1

Named Arguments

function greet($name, $greeting = "Hello") {
  echo "$greeting, $name";
}
greet(name: "Jane", greeting: "Hi");

Attributes (PHP 8+)

#[Route("/api")]
function handler() {}

Match Expression (PHP 8+)

$result = match($status) {
  200 => 'OK',
  404 => 'Not Found',
  default => 'Unknown'
};