ENGIMY.IO - CHEATSHEET
PHP × QUICK REFERENCE
REFERENCE vPHP 8.x

PHP Quick Reference

Everything you need day‑to‑day – syntax, functions, OOP, and web development.

Basic Syntax

// PHP tags
<?php
    // code goes here
?>

// Short tags (if enabled)
<? // code ?>

// Echo / Print
echo "Hello, World!";
print "Hello, World!";
print_r($array);       // print human‑readable
var_dump($variable);   // dump with type and value

// Comments
// Single line
# Single line (Unix style)
/*
    Multi-line comment
*/

Data Types

Scalar Types
  • int42, -5, 0
  • float3.14, 2.0
  • string"hello", 'world'
  • booltrue, false
Compound Types
  • array[1, 2, 3]
  • objectinstance of a class
  • callablefunction reference
  • iterablearrays or Traversable objects
Special Types
  • nullno value
  • resourceexternal resource (file, DB)
  • mixedany type (PHP 8)
  • voidno return value
Type Checking
  • gettype($var)returns type string
  • is_int($var)is integer
  • is_string($var)
  • is_array($var)
  • is_object($var)
  • is_null($var)
  • isset($var)is set and not null
  • empty($var)is empty (0, "", null, false)

Type Conversions

// Explicit cast
$int = (int) "42";
$float = (float) "3.14";
$bool = (bool) 0;        // false
$string = (string) 123;

// Type juggling (implicit)
$sum = "10" + 5;          // int(15)
$concat = "Number: " . 10; // string "Number: 10"

Variables

// Declaration (case‑sensitive)
$name = "Alice";
$age = 25;
$is_active = true;

// Variable variables
$varName = "age";
echo $$varName;           // 25

// Constants
define("APP_NAME", "Engimy");
const VERSION = "1.0.0";  // PHP 5.3+
echo APP_NAME;

// Predefined constants
echo PHP_VERSION;
echo PHP_OS;
echo __LINE__;            // current line
echo __FILE__;            // full file path
echo __DIR__;             // directory of file

Variable Scope

$globalVar = "global";

function testScope() {
    // Access global variable
    global $globalVar;
    echo $globalVar;

    // Static variable (persists across calls)
    static $count = 0;
    $count++;
    echo $count;
}

Operators

Arithmetic
  • + – addition
  • - – subtraction
  • * – multiplication
  • / – division
  • % – modulus
  • ** – exponentiation (PHP 5.6+)
Assignment
  • = – assign
  • +=, -=, *=, /=
  • .= – concatenate
  • ??= – null coalescing assign (PHP 7.4)
  • ?? – null coalescing
Comparison
  • == – equal (loose)
  • === – identical (strict)
  • != / <> – not equal
  • !== – not identical
  • <, >, <=, >=
  • <=> – spaceship (PHP 7)
Logical
  • && / and – AND
  • || / or – OR
  • ! – NOT
  • xor – XOR
Increment / Decrement
  • ++$a – pre‑increment
  • $a++ – post‑increment
  • --$a – pre‑decrement
  • $a-- – post‑decrement
String
  • . – concatenation
  • .= – concatenate assign

Control Flow

if / else

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

switch

switch ($fruit) {
    case "apple":
        echo "It's an apple";
        break;
    case "banana":
        echo "It's a banana";
        break;
    default:
        echo "Unknown fruit";
}

match (PHP 8)

$result = match ($status) {
    200 => "OK",
    404 => "Not Found",
    500 => "Server Error",
    default => "Unknown",
};

Loops

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

// foreach
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo $color;
}
foreach ($colors as $index => $color) {
    echo "$index: $color";
}

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

// do‑while
$i = 0;
do {
    echo $i++;
} while ($i < 5);

// break / continue
for ($i = 0; $i < 10; $i++) {
    if ($i % 2 == 0) continue; // skip evens
    if ($i > 7) break;
    echo $i;
}

Functions

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

// Type hints (PHP 7+)
function greet(string $name, int $age = 25): string {
    return "Hello, $name! You are $age.";
}

// Nullable types (PHP 7.1)
function findUser(int $id): ?User {
    // returns User or null
}

// Union types (PHP 8)
function process(int|string $value): int|false {
    // accepts int or string, returns int or false
}

// Variadic functions
function sum(...$numbers) {
    return array_sum($numbers);
}

// Named arguments (PHP 8)
function greet($name, $greeting = "Hello") {
    echo "$greeting, $name";
}
greet(greeting: "Hi", name: "Alice");

// Anonymous functions / closures
$square = function($x) {
    return $x * $x;
};
echo $square(5);

// Arrow functions (PHP 7.4)
$square = fn($x) => $x * $x;

// Passing by reference
function increment(&$num) {
    $num++;
}

Arrays

Creating Arrays

// Indexed
$colors = ["red", "green", "blue"];
$colors = array("red", "green", "blue");

// Associative
$user = [
    "name" => "Alice",
    "age" => 25,
    "city" => "Delhi"
];

// Multidimensional
$matrix = [
    [1, 2, 3],
    [4, 5, 6]
];

// Short array syntax (PHP 5.4+)
$items = [];

Accessing Arrays

echo $colors[0];            // red
echo $user["name"];         // Alice
echo $matrix[1][2];         // 6

// Add / modify
$colors[] = "yellow";       // append
$user["age"] = 26;

// Remove
unset($colors[1]);
unset($user["age"]);

Array Functions

count($arr)           // length
array_push($arr, $val) // add to end
array_pop($arr)       // remove from end
array_shift($arr)     // remove from start
array_unshift($arr, $val) // add to start
in_array($val, $arr)  // check existence
array_key_exists($key, $arr)
array_keys($arr)      // get all keys
array_values($arr)    // get all values
array_merge($arr1, $arr2) // merge
array_diff($arr1, $arr2) // difference
array_intersect($arr1, $arr2) // intersection
array_map($fn, $arr)  // apply function
array_filter($arr, $fn) // filter
array_reduce($arr, $fn, $initial) // reduce
sort($arr)            // sort (by value)
rsort($arr)           // reverse sort
asort($arr)           // sort (preserve keys)
ksort($arr)           // sort by keys
array_slice($arr, $offset, $length) // slice

Strings

String Types

// Single quotes (literal)
$str = 'Hello $name';      // Hello $name

// Double quotes (variable interpolation)
$str = "Hello $name";      // Hello Alice

// Heredoc (multi‑line)
$str = <<<EOD
    Multi-line
    string
EOD;

// Nowdoc (no interpolation)
$str = <<<'EOD'
    No interpolation
EOD;

String Functions

strlen($str)          // length
strpos($str, $needle) // position (case‑sensitive)
stripos($str, $needle) // position (case‑insensitive)
substr($str, $start, $length) // substring
str_replace($search, $replace, $str) // replace
str_ireplace($search, $replace, $str) // replace (insensitive)
explode($delimiter, $str) // string → array
implode($delimiter, $arr) // array → string
trim($str)            // remove whitespace
ltrim($str)           // remove left whitespace
rtrim($str)           // remove right whitespace
strtolower($str)      // lowercase
strtoupper($str)      // uppercase
ucfirst($str)         // uppercase first
ucwords($str)         // uppercase each word
htmlspecialchars($str) // escape HTML
strip_tags($str)      // remove HTML tags

Superglobals

Request Data
  • $_GETURL parameters
  • $_POSTform data (POST)
  • $_REQUESTGET, POST, COOKIE
  • $_FILESfile uploads
Server / Session
  • $_SERVERserver info
  • $_SESSIONsession data
  • $_COOKIEcookie data
  • $_ENVenvironment variables
  • $GLOBALSglobal variables

Common Server Variables

$_SERVER['HTTP_HOST']    // domain
$_SERVER['REQUEST_URI']  // URL path + query
$_SERVER['REQUEST_METHOD'] // GET, POST, etc.
$_SERVER['REMOTE_ADDR']  // client IP
$_SERVER['HTTP_USER_AGENT'] // browser
$_SERVER['SCRIPT_FILENAME'] // current file

File Handling

// Read file
$content = file_get_contents("file.txt");
$lines = file("file.txt"); // array of lines

// Write file
file_put_contents("file.txt", "Hello World");

// Manual file operations
$handle = fopen("file.txt", "r"); // r, w, a, r+, w+, a+
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);

// Write
$handle = fopen("file.txt", "w");
fwrite($handle, "Hello");
fclose($handle);

// Check if exists / readable / writable
file_exists("file.txt")
is_readable("file.txt")
is_writable("file.txt")

Object‑Oriented Programming

Class Basics

class Person {
    // Properties
    public string $name;
    private int $age;
    protected string $city;

    // Constructor
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
    }

    // Method
    public function greet(): string {
        return "Hello, $this->name";
    }

    // Getter / Setter
    public function getAge(): int {
        return $this->age;
    }
    public function setAge(int $age): void {
        if ($age >= 0) {
            $this->age = $age;
        }
    }
}

// Constructor property promotion (PHP 8)
class User {
    public function __construct(
        public string $name,
        public int $age,
        private string $email
    ) {}
}

Inheritance

class Student extends Person {
    private string $studentId;

    public function __construct(string $name, int $age, string $studentId) {
        parent::__construct($name, $age);
        $this->studentId = $studentId;
    }

    public function greet(): string {
        return "Hello, I'm student " . $this->studentId;
    }
}

Interfaces & Traits

// Interface
interface Greetable {
    public function greet(): string;
}

// Trait
trait Loggable {
    public function log($message) {
        error_log($message);
    }
}

class Employee implements Greetable {
    use Loggable;
    public function greet(): string {
        return "Hello, I'm an employee";
    }
}

Error Handling

// try / catch / finally
try {
    if ($denominator == 0) {
        throw new Exception("Division by zero");
    }
    $result = $numerator / $denominator;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    echo "Cleanup";
}

// Custom exception
class ValidationException extends Exception {}

// Error handling with set_exception_handler
set_exception_handler(function($e) {
    echo "Uncaught: " . $e->getMessage();
});

PDO (Database)

// Connect
$pdo = new PDO(
    "mysql:host=localhost;dbname=mydb;charset=utf8",
    "username",
    "password"
);

// Query
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Prepared statement (secure)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Named placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([':id' => $id]);

// Insert
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["Alice", "alice@example.com"]);

// Error handling
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Sessions & Cookies

// Start session
session_start();

// Set / Get session
$_SESSION['user_id'] = 123;
$id = $_SESSION['user_id'];

// Destroy session
session_destroy();

// Cookie (set / get)
setcookie("theme", "dark", time() + 3600, "/");
$theme = $_COOKIE['theme'] ?? 'light';

Common Built‑in Functions

Date / Time
  • date("Y-m-d H:i:s")
  • time()current timestamp
  • strtotime("+1 day")
  • DateTimeobject‑oriented
JSON
  • json_encode($array)to JSON
  • json_decode($json, true)to array
  • json_last_error()
Math
  • abs(), round(), ceil(), floor()
  • rand(), mt_rand()
  • pow(), sqrt()
  • max(), min()
Filtering
  • filter_var($email, FILTER_VALIDATE_EMAIL)
  • filter_var($url, FILTER_VALIDATE_URL)
  • filter_var($int, FILTER_VALIDATE_INT)
  • filter_input(INPUT_POST, 'field', FILTER_SANITIZE_STRING)

Best Practices

  • Use strict typesdeclare(strict_types=1); at the top of files.
  • Use type hints – for parameters and return values.
  • Avoid global variables – use dependency injection.
  • Use prepared statements – prevents SQL injection.
  • Escape outputhtmlspecialchars() for HTML output.
  • Use namespaces – avoid class name conflicts.
  • Use Composer – for dependency management.
  • Follow PSR‑12 – coding style standard.
  • Use error loggingerror_log() or Monolog.
  • Avoid eval() – dangerous and slow.
  • Use password_hash() and password_verify() for passwords.
  • Keep functions small – single responsibility.
  • Use __autoload or Composer autoload – avoid manual includes.
📌 Quick Reference
Tags: <?php ... ?>
Echo: echo $var or print $var
Types: int, float, string, bool, array, object, null, mixed, void
Superglobals: $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_FILES
String functions: strlen, strpos, substr, str_replace, explode, implode
Array functions: count, in_array, array_push, array_merge, array_map, array_filter
OOP: class, extends, interface, trait, public/private/protected, __construct
DB: PDO prepared statements – prepare(), execute()
Security: htmlspecialchars, password_hash, prepared statements, filter_var
← Back to All Cheatsheets