PHP Reference
Every PHP language construct, operator, function, class and the most-used standard extensions in one place. Concise, accurate pages with live examples that run on PHP 8.5, with syntax, parameters and return values.
Language Constructs and Statements
-
echoOutputs one or more strings. -
printOutputs a string and returns 1. -
if, elseif, elseConditional execution. -
switchMulti-way branching with loose comparison. -
matchStrict comparison expression with no fall-through. -
whileLoops while a condition is true. -
do-whileLoops at least once. -
forCounter-based loops. -
foreachIterates arrays and objects. -
break and continueLeaves or skips loop iterations. -
returnReturns from a function or script. -
gotoJumps to a label (and why to avoid it). -
declarestrict_types, ticks and encoding. -
try, catch, finallyException handling. -
throwThrows an exception, also as an expression. -
include and requireLoads other files (include_once, require_once). -
issetTests whether a variable is set and not null. -
emptyTests whether a value is empty. -
unsetDestroys variables and array elements. -
list and array destructuringUnpacks arrays into variables. -
namespace and useNamespaces, imports and aliases. -
const and defineDefining constants. -
global and staticVariable scope and static variables. -
Heredoc and nowdocMulti-line strings. -
Alternative control syntaxif: endif; and template syntax. -
Closures and arrow functionsfunction () use and fn =>. -
First-class callable syntaxstrlen(...) and $obj->method(...). -
Named argumentsPassing arguments by name. -
Nullsafe operator?-> method and property chaining. -
exit and dieTerminates the script. -
evalEvaluates code from a string (and why to avoid it). -
enumEnumerations: pure and backed enums. -
readonlyReadonly properties and classes. -
Attributes#[Attribute] metadata.
Operators
-
Arithmetic operators+, -, *, /, %, ** and intdiv(). -
Assignment operators=, +=, .=, ??= and friends. -
Comparison operators==, ===, <=>, <, > and type juggling. -
Logical operators&&, ||, !, and, or, xor and precedence. -
String operatorsThe . concatenation operator and .=. -
Array operators+, ==, ===, != on arrays. -
Null coalescing operator?? and ??=. -
Ternary and Elvis operators?: and ? :. -
Spread operator... for arguments and arrays. -
Bitwise operators&, |, ^, ~, << and >>. -
Increment and decrement++ and -- (and string increment). -
instanceofType checks on objects. -
Backtick operatorShell execution and why it is dangerous. -
The @ operatorSuppressing errors (and why not to). -
Operator precedencePrecedence and associativity table. -
new and cloneCreating and copying objects. -
Scope resolution operator:: for static members and constants.
Types and Type Handling
-
boolBooleans and what counts as false. -
intIntegers, overflow and bases. -
floatFloating-point numbers and precision. -
stringStrings, single vs. double quotes, interpolation. -
arrayOrdered maps: syntax and behavior. -
objectObjects and stdClass. -
nullThe null value. -
callableCallable types and strings. -
iterableThe iterable pseudo-type. -
mixed, never and voidSpecial return and parameter types. -
Union, intersection and nullable typesDeclaring complex types. -
Type jugglingAutomatic conversions. -
Type casting(int), (string) and friends. -
strict_typesStrict typing mode. -
resourcesResource values and handles.
Variables and Constants
-
VariablesNaming, assignment and references. -
Variable variables$$name. -
References&$var and reference semantics. -
Variable scopeLocal, global, static scope. -
SuperglobalsOverview of $_GET, $_POST and friends. -
$_GETQuery string parameters. -
$_POSTForm data. -
$_SERVERServer and request information. -
$_REQUESTCombined request data. -
$_SESSIONSession data. -
$_COOKIECookies. -
$_FILESUploaded files. -
$_ENV and getenvEnvironment variables. -
$GLOBALSThe global symbol table. -
Predefined constantsPHP_EOL, PHP_INT_MAX, PHP_VERSION and more. -
Magic constants__LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __METHOD__, __NAMESPACE__. -
Error level constantsE_ALL, E_ERROR, E_WARNING and friends.
String Functions
-
str_contains()Checks whether a string contains a substring. -
str_starts_with()Checks the beginning of a string. -
str_ends_with()Checks the end of a string. -
strlen()Returns the byte length of a string. -
mb_strlen()Returns the character length. -
strpos()Finds the first occurrence. -
stripos()Case-insensitive strpos. -
strrpos()Finds the last occurrence. -
strstr()Returns a string from the first match. -
strrchr()Returns a string from the last match of a character. -
substr()Returns part of a string. -
mb_substr()Multibyte-safe substr. -
substr_count()Counts substring occurrences. -
substr_replace()Replaces part of a string. -
str_replace()Replaces all occurrences. -
str_ireplace()Case-insensitive replacement. -
strtr()Translates characters or substrings. -
str_repeat()Repeats a string. -
str_pad()Pads a string to a length. -
str_split()Splits a string into chunks. -
mb_str_split()Splits into multibyte characters. -
explode()Splits a string by a delimiter. -
implode()Joins array elements with a string. -
trim()Strips whitespace or characters from both ends. -
ltrim()Strips from the start. -
rtrim()Strips from the end. -
strtolower()Converts to lowercase. -
strtoupper()Converts to uppercase. -
mb_strtolower()Multibyte lowercase. -
mb_strtoupper()Multibyte uppercase. -
ucfirst()Uppercases the first character. -
lcfirst()Lowercases the first character. -
ucwords()Uppercases the first letter of each word. -
wordwrap()Wraps text at a width. -
nl2br()Inserts HTML line breaks. -
strrev()Reverses a string. -
strcmp()Binary-safe string comparison. -
strcasecmp()Case-insensitive comparison. -
strncmp()Compares the first n characters. -
strnatcmp()Natural-order comparison. -
similar_text()Similarity between strings. -
levenshtein()Edit distance between strings. -
soundex() and metaphone()Phonetic keys. -
sprintf()Formats a string. -
printf()Prints a formatted string. -
vsprintf() and vprintf()Formats with an array of arguments. -
number_format()Formats a number with separators. -
htmlspecialchars()Escapes HTML special characters. -
htmlspecialchars_decode() and html_entity_decode()Reverses HTML escaping. -
strip_tags()Removes HTML and PHP tags. -
addslashes() and stripslashes()Escapes and unescapes quotes. -
chunk_split()Splits a string into chunks with an ending. -
str_word_count()Counts or lists words. -
ctype functionsctype_alpha, ctype_digit and friends. -
chr() and ord()Characters and byte values. -
bin2hex() and hex2bin()Hexadecimal conversion. -
base64_encode() and base64_decode()Base64 encoding. -
urlencode() and rawurlencode()URL encoding. -
http_build_query()Builds a query string. -
parse_url()Parses a URL into parts. -
parse_str()Parses a query string. -
md5() and sha1()Legacy hashes (not for passwords). -
hash()Computes hashes with many algorithms. -
crc32()CRC-32 checksum. -
uniqid()Generates a unique-ish ID. -
Multibyte string functionsmb_* overview and encodings. -
iconv()Converts character encodings. -
utf8_encode() and utf8_decode()Deprecated conversions and replacements. -
PHP_EOL and line endingsNewlines across platforms.
Array Functions
-
Array functions overviewChoosing between array functions. -
count()Counts elements. -
array_push()Pushes elements onto the end. -
array_pop()Pops the last element. -
array_shift()Removes the first element. -
array_unshift()Prepends elements. -
array_merge()Merges arrays. -
array_merge_recursive()Recursive merge. -
array_replace()Replaces elements by key. -
array_combine()Creates an array from keys and values. -
array_keys()Returns keys. -
array_values()Returns values and reindexes. -
array_key_exists()Checks for a key. -
array_key_first() and array_key_last()First and last keys. -
in_array()Checks for a value. -
array_search()Finds the key of a value. -
array_slice()Extracts a slice. -
array_splice()Removes and replaces elements. -
array_map()Applies a callback to elements. -
array_filter()Filters with a callback. -
array_reduce()Reduces to a single value. -
array_walk()Applies a callback in place. -
array_column()Extracts a column. -
array_unique()Removes duplicates. -
array_reverse()Reverses order. -
array_flip()Swaps keys and values. -
array_fill() and array_fill_keys()Fills arrays. -
array_pad()Pads an array. -
array_chunk()Splits into chunks. -
array_diff()Computes differences. -
array_diff_key()Differences by key. -
array_intersect()Computes intersections. -
array_intersect_key()Intersection by key. -
array_sum()Sum and product. -
array_count_values()Counts value frequencies. -
array_rand()Picks random keys. -
shuffle()Shuffles in place. -
range()Creates a range of values. -
compact()Variables to arrays and back. -
array_is_list()Checks for a list. -
array_find()Search helpers (PHP 8.4). -
array_walk_recursive()Recursive walk. -
array_multisort()Sorts several arrays. -
sort()Sorts values. -
asort() and arsort()Sorts values, keeping keys. -
ksort() and krsort()Sorts by key. -
usort(), uasort() and uksort()Sorts with a callback. -
natsort() and natcasesort()Natural-order sorting. -
Sort flags and stabilitySORT_REGULAR, SORT_STRING and stable sorting. -
current(), next(), reset() and end()The internal array pointer. -
iterator_to_array()Converts iterators to arrays. -
Array keys and castingHow keys are normalized. -
Array unpackingString keys in spread and destructuring.
Math Functions
-
abs()Absolute value. -
ceil() and floor()Rounds up and down. -
round()Rounds a number. -
intdiv()Integer division. -
fmod()Floating-point remainder. -
max() and min()Largest and smallest values. -
pow() and sqrt()Powers and roots. -
exp() and log()Exponential and logarithms. -
Trigonometric functionssin, cos, tan and friends. -
pi() and M_PIPi and math constants. -
rand() and mt_rand()Random numbers (legacy). -
random_int()Cryptographically secure integers. -
random_bytes()Secure random bytes. -
mt_srand()Seeding the generator. -
Random\RandomizerThe object-oriented random API. -
is_nan() and is_infinite()NaN and infinity checks. -
base_convert(), bindec() and decbin()Base conversion. -
hexdec(), dechex(), octdec(), decoct()Hex and octal conversion. -
BCMath functionsArbitrary-precision arithmetic. -
GMP functionsBig integers (extension). -
Floating-point precisionWhy 0.1 + 0.2 != 0.3.
Date and Time
-
time()Current Unix timestamp. -
date()Formats a timestamp. -
mktime()Creates a timestamp from parts. -
strtotime()Parses English date text. -
checkdate()Validates a date. -
date_default_timezone_set()Sets the default time zone. -
microtime() and hrtime()High-resolution time. -
DateTimeMutable date-time objects. -
DateTimeImmutableImmutable date-time objects. -
DateTimeZoneTime zones. -
DateIntervalDurations. -
DatePeriodIterating date ranges. -
Date format charactersThe format character table. -
Comparing and diffing datesdiff(), comparison and modify(). -
date_parse() and getdate()Parsing into arrays. -
sleep() and usleep()Pausing execution.
Functions and Classes
-
Defining functionsDeclaring functions, parameters, return types. -
Default parameter valuesDefaults and optional arguments. -
Variadic functions...$args and func_get_args(). -
Passing by referenceReference parameters. -
RecursionRecursive functions and limits. -
Anonymous functionsClosures in depth. -
Callbackscall_user_func and callable strings. -
call_user_func() and call_user_func_array()Calling callables. -
function_exists()Checking for functions. -
func_get_args()Argument introspection. -
Generatorsyield, yield from and Generator. -
Classes and objectsDeclaring classes. -
PropertiesDeclaring properties and types. -
Constructor promotionProperty promotion in constructors. -
Visibilitypublic, protected, private. -
static properties and methodsStatic members and late static binding. -
Class constantsconst, final and typed constants. -
Inheritanceextends, parent, final. -
Abstract classesabstract classes and methods. -
Interfacesinterface and implements. -
TraitsReusing code with traits. -
Magic methods__construct, __get, __call, __toString and more. -
__invokeInvokable objects. -
Object cloning__clone and deep copies. -
Comparing objects== vs. === -
Autoloadingspl_autoload_register and PSR-4. -
Late static bindingstatic:: vs. self::. -
Property hooksget and set hooks (PHP 8.4). -
Asymmetric visibilitypublic private(set) (PHP 8.4). -
new in initializersObjects as default values. -
StringableThe Stringable interface. -
class_exists() and friendsClass introspection functions. -
get_class() and get_object_vars()Object introspection. -
method_exists() and property_exists()Member checks. -
ReflectionReflectionClass and friends. -
serialize() and unserialize()PHP serialization. -
var_export()Exportable representations. -
var_dump(), print_r() and debug helpersInspecting values. -
gettype(), settype() and get_debug_type()Type functions. -
is_* type checksis_int, is_string, is_array and more. -
intval(), floatval() and strval()Conversion functions. -
filter_var()Validation and sanitization. -
filter_input()Filtering request input. -
json_encode()Converts values to JSON. -
json_decode()Parses JSON. -
JSON errors and flagsJSON_THROW_ON_ERROR and friends.
Exceptions and Errors
-
ExceptionThe base exception class. -
ErrorThe base engine error class. -
ThrowableThe root interface. -
TypeErrorType mismatches. -
ValueErrorValid type, invalid value. -
ArgumentCountErrorToo few arguments. -
ArithmeticError and DivisionByZeroErrorMath errors. -
InvalidArgumentExceptionSPL logic exceptions. -
RuntimeExceptionSPL runtime exceptions. -
JsonExceptionJSON failures. -
Error reportingerror_reporting, display_errors, ini settings. -
set_error_handler()Custom error handlers. -
set_exception_handler()Global exception handlers. -
trigger_error()Raising errors. -
error_log()Writing to the log. -
assert()Assertions. -
Custom exceptionsDesigning exception hierarchies. -
finally in depthCleanup semantics.
Files and I/O
-
fopen()Opens a file or stream. -
fread() and fwrite()Reading and writing handles. -
fgets() and fgetc()Reading lines and characters. -
fclose()Closes a handle. -
file_get_contents()Reads a whole file. -
file_put_contents()Writes a whole file. -
file()Reads a file into an array. -
feof(), fseek() and ftell()Stream position. -
fputcsv() and fgetcsv()CSV reading and writing. -
str_getcsv()Parses a CSV string. -
file_exists() and is_file()Checking files. -
is_dir() and mkdir()Directories. -
unlink(), rename() and copy()Deleting, renaming, copying. -
scandir(), glob() and opendir()Listing directories. -
filesize(), filemtime() and stat()File information. -
pathinfo(), basename() and dirname()Path parts. -
realpath()Resolving paths. -
tempnam(), tmpfile() and sys_get_temp_dir()Temporary files. -
flock()File locking. -
php://stdin, php://memory and wrappersStream wrappers. -
Stream contextsstream_context_create basics. -
SplFileObjectObject-oriented file access. -
Output bufferingob_start and friends. -
ini_set() and ini_get()Runtime configuration. -
PHP_SAPI and php_sapi_name()CLI vs. web. -
$argv, $argc and getopt()Command-line arguments. -
fscanf() and sscanf()Parsing formatted input.
Regular Expressions
-
preg_match()Matches a pattern once. -
preg_match_all()Matches all occurrences. -
preg_replace()Replaces by pattern. -
preg_replace_callback()Replaces with a callback. -
preg_split()Splits by pattern. -
preg_quote()Escapes regex characters. -
preg_grep()Filters an array by pattern. -
preg_last_error()Regex errors. -
PCRE syntaxDelimiters, modifiers, groups, lookarounds. -
Pattern modifiersi, m, s, x, u and others. -
Named groups and flagsPREG_SET_ORDER, named captures.
Standard PHP Library and Classes
-
ArrayObject and ArrayIteratorArray-like objects. -
SplStack, SplQueue and SplDoublyLinkedListStacks and queues. -
SplObjectStorageObject sets and maps. -
SplPriorityQueue and SplHeapPriority queues and heaps. -
SplFixedArrayFixed-size arrays. -
Iterator and IteratorAggregateMaking objects iterable. -
Countablecount() on objects. -
ArrayAccessArray syntax on objects. -
JsonSerializableCustom JSON. -
ClosureClosure binding and fromCallable. -
WeakMap and WeakReferenceWeak references. -
stdClassThe generic object. -
SPL iteratorsLimit, Filter, Recursive and more. -
SPL exceptionsThe SPL exception hierarchy. -
Random\Engine classesMt19937, Xoshiro256StarStar. -
Uri\Rfc3986\UriThe URI extension (PHP 8.5). -
Intl classesNumberFormatter and IntlDateFormatter (extension). -
NumberFormatterLocale-aware formatting.
Databases (PDO)
-
PDOConnecting and options. -
PDO::query()Running queries. -
PDO::prepare()Prepared statements. -
PDOStatement::fetch()Fetch modes. -
PDOStatement::fetchAll()Fetching all rows. -
bindParam() and bindValue()Binding parameters. -
PDO transactionsbeginTransaction, commit, rollBack. -
PDO error handlingError modes and exceptions. -
PDO::lastInsertId()Generated keys. -
PDO and SQLiteIn-memory databases. -
mysqli overviewThe MySQL extension (read-only). -
SQL injectionPrevention with prepared statements.
Web and Security
-
header()Sending HTTP headers. -
http_response_code()Setting status codes. -
setcookie()Setting cookies. -
Sessionssession_start and session handling. -
password_hash()Hashing passwords. -
password_verify()Verifying passwords. -
hash_hmac() and hash_equals()HMAC and timing-safe comparison. -
openssl_encrypt()Encryption (extension). -
Sodium functionsModern cryptography (extension). -
CSRF protectionTokens and same-site cookies. -
XSS preventionEscaping output. -
File uploadsmove_uploaded_file and validation. -
cURLHTTP clients (extension, read-only). -
mail()Sending email (and alternatives). -
ComposerDependencies and autoloading (read-only). -
php.iniConfiguration directives. -
OPcacheBytecode caching.
Concepts and Reference
-
PHP version historyWhat changed in 8.0โ8.5. -
PHP 8 feature tourUnion types, match, attributes, enums, readonly, fibers. -
FibersCooperative multitasking. -
Deprecated featuresThings to stop using. -
PSR standardsPSR-1, 4, 12 and the PHP-FIG. -
Coding standardsNaming and formatting. -
PHP command lineRunning scripts and options. -
Memory and garbage collectionReference counting and the GC. -
Performance tipsCommon performance practices. -
Security checklistA practical checklist. -
Reserved keywordsThe keyword list. -
PHP tags<?php, <?=, closing tags. -
Comments//, # and docblocks. -
Loose comparison tablesPHP 8 comparison rules. -
GlossaryKey PHP terms.
Nothing matches โโ. Try the site search.