PHP logoPHP BEGINNER

PHP Fundamentals

Modern PHP 8+ syntax, features, and best practices for building robust web applications

12 min read
phpphp8backendweblaravelsymfonycomposeroop

Setup & Basics

Getting started with PHP

Installation & Setup

Installing PHP and setting up development environment

php
🚀 PHP 8.3 brings major performance improvements
📦 Composer is the standard dependency manager
🔧 Built-in server perfect for development
⚡ PHP-FPM recommended for production

PHP Syntax Basics

Basic PHP syntax and structure

php
💡 PHP files start with <?php tag
📌 Variables always start with $ sign
⚡ Use require for critical files, include for optional
🔥 Constants are globally accessible and immutable

Data Types

PHP data types and type declarations

php
💡 PHP is dynamically typed but supports type hints
⚡ Use strict_types=1 for type safety
📌 Union types allow multiple possible types
🔥 Never type indicates function never returns

Control Structures

Conditionals, loops, and control flow

Conditionals

If statements, switch, and match expressions

php
💡 Match is stricter than switch (no type coercion)
⚡ Null coalescing (??) simplifies default values
📌 Match returns values, switch executes code
🔥 Alternative syntax cleaner for templates

Loops

Different types of loops in PHP

php
💡 Use foreach for arrays, for when you need index
⚡ Reference (&) in foreach allows modification
📌 Always unset references after foreach
🔥 Break/continue can specify nesting level

Functions & Closures

Functions, closures, and arrow functions

Functions

Function declaration and parameters

php
💡 Named arguments improve readability
⚡ Variadic functions accept unlimited arguments
📌 Pass by reference with & to modify variables
🔥 Type hints catch errors early

Closures & Arrow Functions

Anonymous functions and arrow functions

php
💡 Arrow functions auto-capture parent scope
⚡ Use & to modify external variables in closures
📌 Arrow functions always return (no void)
🔥 First-class callables simplify syntax in PHP 8.1+

Arrays

Array manipulation and operations

Array Basics

Creating and accessing arrays

php
💡 Use [] syntax for arrays (modern PHP)
⚡ Spread operator (...) unpacks arrays
📌 array_key_exists vs isset: isset returns false for null
🔥 Destructuring makes code cleaner

Array Functions

Built-in array manipulation functions

php
💡 array_map transforms, array_filter selects, array_reduce aggregates
⚡ Spaceship operator (<=>) simplifies comparisons
📌 array_merge re-indexes, + operator preserves keys
🔥 array_column great for extracting from multi-dimensional arrays

Object-Oriented PHP

Classes, objects, and OOP concepts

Classes & Objects

Basic class definition and object creation

php
💡 Constructor property promotion reduces boilerplate
⚡ Readonly properties ensure immutability
📌 Use visibility modifiers for encapsulation
🔥 Static properties/methods shared across all instances

Inheritance & Interfaces

Extending classes and implementing interfaces

php
💡 Interfaces define contracts, abstract classes provide partial implementation
⚡ Traits enable horizontal code reuse
📌 Use final to prevent inheritance
🔥 Late static binding with static:: for proper inheritance

PHP 8 Features

Modern PHP 8+ features and improvements

PHP 8.0 Features

Major features introduced in PHP 8.0

php
💡 Match expressions are safer than switch (no fall-through)
⚡ Nullsafe operator prevents null reference errors
📌 Constructor promotion reduces boilerplate significantly
🔥 JIT compilation dramatically improves CPU-intensive tasks

PHP 8.1+ Features

Features from PHP 8.1, 8.2, and 8.3

php
💡 Enums provide type-safe constants with methods
⚡ Readonly properties/classes ensure immutability
📌 First-class callables simplify functional programming
🔥 Fibers enable async programming without callbacks

Error Handling

Exception handling and error management

Exceptions

Working with exceptions and try-catch blocks

php
💡 Use specific exception types for different errors
⚡ Finally block always executes for cleanup
📌 Chain exceptions to preserve error context
🔥 Throwable catches both Exception and Error types

Database & PDO

Database connections and operations with PDO

PDO Basics

Connecting to databases and executing queries

php
💡 Always use prepared statements to prevent SQL injection
⚡ Use transactions for related operations
📌 PDO supports multiple databases with same interface
🔥 Set PDO::ERRMODE_EXCEPTION for better error handling

String Manipulation

Working with strings in PHP

String Operations

Common string manipulation functions

php
💡 Use mb_* functions for multibyte (UTF-8) strings
⚡ str_contains/starts_with/ends_with are PHP 8.0+ additions
📌 Always use htmlspecialchars() for user input in HTML
🔥 Heredoc parses variables, Nowdoc does not

File Handling

Reading and writing files

File Operations

Working with files and directories

php
💡 Use file_get_contents for simple reads, handles for large files
⚡ Always check file_exists() before operations
📌 Use LOCK_EX flag to prevent race conditions
🔥 Set proper permissions (0755 for dirs, 0644 for files)

Web Features

Sessions, cookies, and HTTP handling

Sessions & Cookies

Managing user sessions and cookies

php
💡 session_start() must be called before any output
⚡ Use secure, httponly, and samesite for cookie security
📌 Always exit() after header redirects
🔥 Regenerate session ID after login to prevent fixation

JSON & APIs

Working with JSON and building APIs

php
💡 Always validate JSON with json_last_error()
⚡ Use php://input for raw POST data
📌 Set proper Content-Type and status codes
🔥 json_validate() in PHP 8.3+ checks without decoding

Advanced Features

Generators, regex, and namespaces

Generators & Iterators

Memory-efficient iteration with generators

php
💡 Generators use yield to pause and resume execution
⚡ Perfect for processing large datasets with low memory
📌 yield from delegates to another generator
🔥 Generators maintain state between iterations

Regular Expressions

Pattern matching with regex

php
💡 Use preg_quote() to escape user input in patterns
⚡ Named groups make matches more readable
📌 Add pattern modifiers: i (case), m (multiline), s (dotall)
🔥 preg_replace_callback for complex replacements

More PHP Cheat Sheets