PHP Tutorial
Learn PHP
The popular server-side scripting language.
Stage 1
01
Getting Started
02
Variables and Constants
04
Strings
05
Numbers, Math and Operators
Stage 2
06
Arrays
07
Conditionals and Loops
Stage 3
09
Object-Oriented PHP
10
Advanced OOP
Stage 4
11
Operators in Depth
- Arithmetic Operators, In Depth
- String Concatenation with .
- Comparison and the Spaceship <=>
- Logical Operators and Short-Circuiting
- Bitwise Operators and Flags
- Null Coalescing ?? and ??=
- Ternary ?: and the Short Ternary
- The Nullsafe Operator ?->
- match vs switch
- The instanceof Operator
- Operator Precedence and Associativity
12
Modern PHP
13
Errors and Exceptions
14
Composer and Autoloading
Stage 5
15
Superglobals and Dates
16
HTTP, Forms and Uploads
17
Sessions and Cookies
18
Databases with PDO
Stage 6
19
Security
20
Testing
Stage 7
22
JSON and APIs
PHP Reference
505 pages · 19 groups · syntax, parameters and worked examples
Array Functions78
array_change_key_caseReturns a copy of an array with all string keys converted to lower or upper case.array_chunkSplits an array into a list of smaller arrays of a given maximum size.array_columnExtracts the values of a single column from a multi-dimensional array or array of objects.array_combineCreates an array by using one array for keys and another array for the matching values.array_count_valuesCounts how many times each distinct value occurs in an array and returns value => count pairs.array_diffReturns the values of the first array that are not present in any of the other arrays.array_diff_assocReturns entries of the first array whose key and value pair is not found in any other array.array_diff_keyReturns entries of the first array whose keys are not present in any of the other arrays.array_diff_uassocCompares arrays by key and value, using a user callback to decide when two keys are equal.array_diff_ukeyReturns entries of the first array whose keys a user callback does not match in any other array.array_fillCreates an array of a given size where every element holds the same value.array_fill_keysCreates an array using the given values as keys, all set to the same value.array_filterFilters an array with a callback, keeping only the elements for which the callback returns true.array_flipSwaps every key with its value, turning an array's values into keys and its keys into values.array_intersectReturns the values of the first array that are also present in every other array passed to it.array_intersect_assocReturns the entries whose key and value both match in every array passed to it.array_intersect_keyKeeps the entries of the first array whose keys also exist in every other array.array_intersect_uassocIntersects arrays on key and value, comparing the keys with a callback you supply.array_intersect_ukeyKeeps the entries whose keys exist in every array, using a callback to decide when two keys are equal.array_is_listTells you whether an array has consecutive integer keys starting at zero.array_key_existsChecks whether a key is present in an array, even when its value is null.array_key_firstReturns the first key of an array without moving the internal array pointer.array_key_lastReturns the last key of an array without moving the internal array pointer.array_keysReturns all the keys of an array, or only the keys whose value matches a given search value.array_mapApplies a callback to every element of one or more arrays and returns the results as a new array.array_mergeCombines arrays into one, overwriting duplicate string keys and renumbering all integer keys.array_merge_recursiveMerges arrays recursively, combining values that share a string key into a nested array.array_multisortSorts several arrays at once, or a multidimensional array, by one or more columns in place.array_padReturns a copy of an array padded with a value to a given length, on the right or the left.array_popRemoves and returns the last element of an array, shortening the array by one.array_productMultiplies all values in an array together and returns the product as an int or float.array_pushAppends one or more values to the end of an array and returns the new element count.array_randPicks one or more random keys from an array without repeating a key in the same call.array_reduceReduces an array to a single value by running a callback that accumulates a carry across elements.array_replaceReplaces values in the first array with values from later arrays that share the same key.array_replace_recursiveReplaces values from later arrays into the first array, descending into nested arrays as it goes.array_reverseReturns a new array with the elements in reverse order, optionally keeping numeric keys.array_searchReturns the key of the first array element matching a value, or false if it is not found.array_shiftRemoves the first element of an array, returns it, and reindexes the remaining numeric keys.array_sliceExtracts a portion of an array by offset and length without modifying the original.array_spliceRemoves a portion of an array in place and optionally replaces it with new elements.array_sumAdds up all the values in an array and returns the total as an int or float.array_udiffCompares arrays by value using a callback and returns the values only present in the first array.array_udiff_assocReturns entries of the first array whose key/value pair is absent from the others, comparing values with a callback.array_uintersectReturns the values present in every array, compared with a callback you supply.array_uniqueRemoves duplicate values from an array, keeping the first occurrence and its key.array_unshiftPrepends one or more values to the front of an array and returns the new element count.array_valuesReturns all the values of an array reindexed numerically from zero, discarding the original keys.array_walkApplies a user callback to every element of an array, optionally modifying values in place.array_walk_recursiveApplies a user callback to every leaf value of a multidimensional array, descending into nested arrays.arsortSorts an array in place by value in descending order while keeping each value bound to its key.asortSorts an array in place by value in ascending order while keeping each value bound to its key.compactBuilds an array from existing variables, using each variable's name as the key.countCounts the elements in an array or a Countable object, optionally descending into nested arrays.currentReturns the value the array's internal pointer is on, without moving the pointer.endMoves an array's internal pointer to the last element and returns that element's value.extractCreates variables in the current scope from an array's keys and values.in_arrayChecks whether a value exists anywhere in an array, with optional strict type comparison.keyReturns the key at the array's current internal pointer position, without moving the pointer.krsortSorts an array in place by key in descending order, keeping every key attached to its value.ksortSorts an array in place by its keys in ascending order, keeping key/value pairs intact.natcasesortSorts an array by value using a case-insensitive natural order algorithm, preserving keys.natsortSorts an array by value using a natural order algorithm, keeping key/value associations.nextAdvances an array's internal pointer one position and returns the value found there.prevRewinds an array's internal pointer one position and returns the value found there.rangeCreates an array containing a sequence of numbers or characters between two boundaries.resetRewinds an array's internal pointer to the first element and returns that element's value.rsortSorts an array by value in descending order and reindexes it with fresh numeric keys.shuffleRandomizes the order of an array's elements in place and reindexes it from zero.sortSorts an array by value in ascending order and reindexes it with fresh numeric keys.uasortSorts an array by value using a custom comparison callback while preserving keys.uksortSorts an array by its keys using a custom comparison callback, keeping values attached.usortSorts an array in place using a user-defined comparison callback, discarding the existing keys.listDestructures an array into several separate variables in a single assignment.eachReturns the current key/value pair of an array and advances the pointer; removed in PHP 8.0.sizeofCounts the elements in an array or Countable object; an alias of count().key_existsChecks whether a key exists in an array, even when its value is null; an alias of array_key_exists().joinJoins array elements into one string separated by a given string; an alias of implode().
Array Functions (PHP 8.4+)6
array_allChecks whether a callback returns true for every element of an array, short-circuiting on the first failure.array_anyChecks whether a callback returns true for at least one element of an array, stopping at the first match.array_findReturns the value of the first array element for which a callback returns true, or null if none match.array_find_keyReturns the key of the first array element for which a callback returns true, or null if none match.array_firstReturns the first value of an array without moving the internal pointer, or null if the array is empty.array_lastReturns the last value of an array without moving the internal pointer, or null if the array is empty.
String Functions80
addslashesEscapes single quotes, double quotes, backslashes and NUL bytes in a string with backslashes.bin2hexConverts binary data into its lowercase hexadecimal string representation, two characters per byte.chrReturns a one-byte string for the given code point between 0 and 255.chunk_splitSplits a string into fixed-length chunks and inserts a separator after each one.count_charsReturns per-byte frequency information for a string, as an array of counts or a string of characters.explodeSplits a string into an array on a given separator, with an optional limit on the number of pieces.hex2binDecodes a hexadecimal string back into the binary data it represents, two characters per byte.html_entity_decodeConverts every HTML entity in a string back to its corresponding character.htmlentitiesConverts every character that has an HTML named entity into that entity.htmlspecialcharsConverts the five HTML-significant characters into entities so text is safe to print in a page.htmlspecialchars_decodeConverts the entities produced by htmlspecialchars back into their plain characters.implodeJoins the elements of an array into a single string, optionally separated by a given string.lcfirstLowercases the first character of a string, leaving the rest of the string untouched.levenshteinCalculates the edit distance between two strings — the number of changes needed to turn one into the other.ltrimStrips whitespace or a given set of characters from the beginning of a string.nl2brInserts an HTML line break before every newline in a string.number_formatFormats a number with grouped thousands and a fixed number of decimal places.ordReturns the integer value 0–255 of the first byte of a string.parse_strParses a URL query string into an array of variables.printfOutputs a formatted string built from a format template and its arguments.quotemetaEscapes a small set of regular-expression metacharacters in a string with backslashes.rtrimStrips whitespace or a given set of characters from the end of a string.similar_textCounts the matching characters between two strings and optionally reports a similarity percentage.soundexCalculates a four-character phonetic key so similar-sounding words share the same code.metaphoneCalculates a phonetic key for an English word so similar-sounding words compare as equal.sprintfReturns a string built from a format template with values substituted into its placeholders.sscanfParses a string according to a format template and returns the extracted values.str_containsChecks whether a string contains a given substring, case-sensitively.str_decrementReturns the previous value of an alphanumeric string, reversing PHP's string increment.str_ends_withChecks whether a string ends with a given substring, case-sensitively.str_getcsvParses one line of CSV text into an array of fields.str_incrementReturns the next value of an alphanumeric string, carrying over like a spreadsheet column.str_ireplaceReplaces all case-insensitive occurrences of a search string with a replacement string.str_padPads a string to a given length with another string, on the left, right or both sides.str_repeatReturns a string made of the input repeated a given number of times.str_replaceReplaces all occurrences of a search string with a replacement string in a string or array.str_rot13Applies the ROT13 substitution cipher to a string, rotating each letter 13 places in the alphabet.str_shuffleRandomly shuffles the characters of a string and returns the result as a new string.str_splitSplits a string into an array of chunks of a given byte length, one byte per element by default.str_starts_withChecks whether a string begins with a given substring, returning true or false.str_word_countCounts the words in a string, or returns them as an array, optionally with their byte positions.strcasecmpCompares two strings case-insensitively and returns a negative, zero or positive integer.strcmpCompares two strings byte by byte and returns a negative, zero or positive integer.strcspnReturns the length of the initial run of a string that contains none of the given characters.strip_tagsRemoves HTML, XML and PHP tags from a string, optionally keeping a list of allowed tags.stripslashesRemoves backslash escape characters from a string, undoing what addslashes added.striposFinds the position of the first case-insensitive occurrence of a substring in a string.stristrReturns the part of a string from the first case-insensitive match of a substring onwards.strlenReturns the number of bytes in a string, not the number of characters.strnatcasecmpCompares two strings in human "natural" order, ignoring letter case.strnatcmpCompares two strings in human "natural" order, treating digit runs as numbers.strncasecmpCompares the first n bytes of two strings without regard to letter case.strncmpCompares the first n bytes of two strings, case sensitively and binary safely.strpbrkReturns the rest of a string starting at the first occurrence of any of the given characters.strposFinds the position of the first occurrence of a substring in a string.strrchrReturns the part of a string from the last occurrence of a character to the end.strrevReturns a string with its bytes in reverse order.strriposFinds the position of the last occurrence of a substring, ignoring letter case.strrposFinds the position of the last occurrence of a substring in a string.strspnReturns the length of the leading run of characters that all belong to a given set.strstrReturns the part of a string from the first occurrence of a substring onward, or the part before it.strtokSplits a string into tokens one at a time, using any of the given delimiter characters.strtolowerConverts all ASCII uppercase letters in a string to lowercase.strtoupperConverts all ASCII lowercase letters in a string to uppercase.strtrReplaces characters or whole substrings in a string using a translation table or two character maps.substrReturns a portion of a string starting at a given offset, optionally limited to a length.substr_compareCompares part of one string with another string, starting at a given offset, without copying it.substr_countCounts how many non-overlapping times a substring occurs in a string.substr_replaceReplaces or inserts text at a given offset and length inside a string, or inside every string of an array.trimRemoves whitespace or other given characters from both ends of a string.ucfirstConverts the first character of a string to uppercase if it is an ASCII letter.ucwordsConverts the first character of each word in a string to uppercase.vsprintfFormats a string using values taken from an array instead of separate arguments.vprintfPrints a formatted string using values from an array and returns the output length.wordwrapWraps a string onto multiple lines at a given width, breaking on spaces.addcslashesAdds backslashes before a chosen set of characters, using C-style escape sequences.stripcslashesRemoves backslashes and decodes C-style escape sequences in a string.get_html_translation_tableReturns the character-to-entity table used internally by htmlspecialchars and htmlentities.utf8_encodeConverts an ISO-8859-1 string to UTF-8; deprecated since PHP 8.2.money_formatFormatted a number as a locale-aware currency string; removed in PHP 8.0.
Math Functions53
absReturns the absolute value of a number, keeping int input as int and float input as float.acosReturns the arc cosine of a number in radians, the inverse of cos().acoshReturns the inverse hyperbolic cosine of a number, the value whose hyperbolic cosine is that number.asinReturns the arc sine of a number in radians, the inverse of sin().asinhReturns the inverse hyperbolic sine of a number, defined for every real value.atanReturns the arc tangent of a number in radians, the inverse of tan().atan2Returns the arc tangent of y/x in radians, using both signs to pick the correct quadrant.atanhReturns the inverse hyperbolic tangent of a number, defined for values between -1 and 1.base_convertConverts a number string from one base to another, for any base between 2 and 36.bindecConverts a binary string to its decimal value, returning an int or a float when too large.ceilRounds a number up to the next whole value and always returns it as a float.cosReturns the cosine of an angle given in radians.coshReturns the hyperbolic cosine of a number, defined as (exp(x) + exp(-x)) / 2.decbinConverts a decimal integer to its binary string representation.dechexConverts a decimal integer to its lowercase hexadecimal string representation.decoctConverts a decimal integer to its octal string representation.deg2radConverts an angle from degrees to its equivalent value in radians.expReturns e raised to the power of the given number.expm1Returns exp(x) - 1 computed accurately even when x is very close to zero.fdivDivides two numbers under IEEE 754 rules, returning INF or NAN instead of throwing on division by zero.floorRounds a number down to the nearest integer and returns it as a float.fmodReturns the floating point remainder of dividing one number by another.fpowRaises one number to the power of another under IEEE 754 rules, always returning a float.hexdecConverts a hexadecimal string to its decimal number equivalent.hypotCalculates the length of the hypotenuse of a right triangle, or a point's distance from the origin.intdivDivides one integer by another and returns the integer quotient, truncated toward zero.is_finiteChecks whether a float is a finite number, returning false for INF, -INF and NAN.is_infiniteChecks whether a float is positive or negative infinity.is_nanChecks whether a float is NAN, the value that comparison operators can never detect.logReturns the natural logarithm of a number, or its logarithm in any base you supply.log10Returns the base-10 logarithm of a number.log1pComputes log(1 + x) accurately even when x is very close to zero.maxReturns the highest value from a list of arguments or from a single array.minReturns the lowest value from a list of arguments or from a single array.octdecConverts a string of octal digits to its decimal integer value.piReturns an approximation of pi as a float, identical to the M_PI constant.powRaises a base number to the power of an exponent and returns the result.rad2degConverts an angle expressed in radians to its equivalent in degrees.roundRounds a number to a given number of decimal places using a chosen rounding mode.sinReturns the sine of an angle given in radians, as a float between -1 and 1.sinhReturns the hyperbolic sine of a number, equal to (exp(x) - exp(-x)) / 2.sqrtReturns the square root of a number, or NAN when the input is negative.tanReturns the tangent of an angle given in radians, equal to sin(x) divided by cos(x).tanhReturns the hyperbolic tangent of a number, an S-shaped value strictly between -1 and 1.mt_randGenerates a pseudo-random integer, optionally within an inclusive minimum and maximum.mt_srandSeeds the Mersenne Twister generator so mt_rand() produces a repeatable sequence.mt_getrandmaxReturns the largest integer mt_rand() can produce when called with no arguments.randGenerates a pseudo-random integer, optionally between an inclusive minimum and maximum.srandSeeds PHP's general-purpose random number generator so rand() produces a repeatable sequence.getrandmaxReturns the largest integer that rand() can possibly return on this system.random_intGenerates a cryptographically secure, uniformly distributed integer between a minimum and maximum.random_bytesGenerates a string of cryptographically secure random bytes of the requested length.lcg_valueReturns a pseudo-random float between 0 and 1 from a combined linear congruential generator.
Date & Time Functions21
checkdateChecks whether a month, day and year form a real Gregorian calendar date, leap years included.dateFormats a Unix timestamp as a string using the script's default timezone.date_default_timezone_getReturns the timezone identifier currently used by all date and time functions in the script.date_default_timezone_setSets the timezone that every date and time function in the script will use from that point on.date_diffReturns the difference between two date objects as a DateInterval of years, months, days and time.date_parseParses a date/time string and returns its components plus any parsing errors and warnings as an array.date_parse_from_formatParses a date/time string against a given format and returns its components plus any errors and warnings.getdateReturns an array of date and time components for a Unix timestamp in the default timezone.gettimeofdayReturns the current time with microsecond precision, as an array or as a float.gmdateFormats a Unix timestamp as a string in UTC, ignoring the script's default timezone.gmmktimeBuilds a Unix timestamp from date and time parts interpreted as UTC rather than local time.hrtimeReturns the system's monotonic high resolution time in nanoseconds, for measuring elapsed time.idateFormats a Unix timestamp with a single format character and returns the result as an integer.localtimeBreaks a Unix timestamp into its local date and time components as an array.microtimeReturns the current Unix timestamp including microseconds, as a string or a float.mktimeBuilds a Unix timestamp from individual hour, minute, second, month, day and year values.strtotimeParses an English date or time description into a Unix timestamp.timeReturns the current time as the number of seconds since the Unix epoch.timezone_identifiers_listReturns an array of all IANA time zone identifiers PHP knows about, optionally filtered.timezone_offset_getReturns a time zone's offset from UTC, in seconds, for a specific date and time.strftimeFormats a timestamp using locale-aware C-style format codes; deprecated since PHP 8.1.
Filesystem Functions59
basenameReturns the trailing name component of a path, optionally with a given suffix removed.clearstatcacheClears PHP's cached file status information so the next stat call reads fresh data from disk.copyCopies a file from a source path to a destination path, overwriting the destination if it exists.dirnameReturns the parent directory of a path, optionally going up several levels.fcloseCloses an open file pointer, flushing any buffered writes and releasing the handle.feofTests whether a file pointer has reached the end of the file or hit a read error.fflushForces PHP's buffered output for an open stream to be written out to the operating system.fgetcReads and returns a single byte from an open file pointer, or false at end of file.fgetcsvReads one line from an open file pointer and parses it as CSV, returning the fields as an array.fgetsReads one line from an open file pointer, including the trailing newline, or false at end of file.fileReads an entire file into an array, with one element per line.file_existsChecks whether a file or directory exists at the given path.file_get_contentsReads an entire file into a string in one call, with optional offset and length.file_put_contentsWrites a string, array or stream to a file in one call, creating the file if needed.fileatimeReturns the Unix timestamp of when a file was last read or accessed.filemtimeReturns the Unix timestamp of when a file's contents were last modified.filepermsReturns a file's permission bits and type as a numeric mode integer.filesizeReturns the size of a file in bytes.filetypeReturns the type of a path as a string, such as file, dir, link or fifo.flockApplies or releases an advisory shared or exclusive lock on an open file handle.fnmatchMatches a string against a shell wildcard pattern using *, ? and character classes.fopenOpens a file or URL and returns a stream resource for reading or writing.fpassthruReads a file handle from its current position to EOF and writes it straight to output.fputcsvFormats an array as a CSV line and writes it to an open file handle.freadReads up to a given number of bytes from an open file or stream handle.fscanfParses one line from an open file according to a printf-style format string.fseekMoves the read/write pointer of an open stream to a given byte offset.fstatReturns size, timestamps and permission information for an already open stream.ftellReturns the current byte position of the read/write pointer in an open stream.ftruncateShortens or extends an open file to an exact size in bytes.fwriteWrites a string to an open file or stream and returns the number of bytes written.globFinds all pathnames matching a shell wildcard pattern and returns them as an array.is_dirTells whether a given path exists and is a directory.is_executableTells whether a path exists and is executable by the current process user.is_fileTells whether a given path exists and is a regular file.is_linkTells whether a given path is a symbolic link, without following it.is_readableChecks whether a file or directory exists and can be opened for reading by the current process.is_uploaded_fileChecks whether the given path is a file that was uploaded to this request via HTTP POST.is_writableChecks whether a file or directory exists and can be written to by the current process.mkdirCreates a directory, optionally creating every missing parent directory along the path.move_uploaded_fileMoves a file uploaded via HTTP POST to a permanent location, verifying it really was an upload.parse_ini_fileReads a configuration file in php.ini format and returns its settings as an array.parse_ini_stringParses a string in php.ini format and returns its settings as an array.pathinfoSplits a file path into its directory, base name, extension and file name components.readfileReads a file and writes it straight to the output buffer, returning the number of bytes sent.readlinkReturns the target path stored in a symbolic link, without following it any further.realpathExpands a path into a canonical absolute path, resolving symlinks, ., .. and duplicate slashes.renameRenames or moves a file or directory, overwriting an existing destination file.rewindMoves a stream's internal file pointer back to the start of the file.rmdirRemoves an empty directory from the filesystem.statReturns an array of information about a file, including size, permissions and timestamps.tempnamCreates a uniquely named empty file in a directory and returns its full path.tmpfileCreates a temporary file open for reading and writing that is deleted when closed.touchSets a file's modification and access times, creating the file if it does not exist.unlinkDeletes a file from the filesystem.disk_free_spaceReturns the number of free bytes available on the filesystem holding a directory.fputsWrites a string to an open file stream; an alias of fwrite.fdatasyncFlushes a stream's buffered data to physical storage without syncing file metadata.fsyncFlushes a stream's buffered data and metadata to physical storage.
Variable & Type Functions31
boolvalConverts any value to a boolean using PHP's standard truthiness rules.floatvalConverts a value to a float, reading the leading numeric part of a string.get_debug_typeReturns the type name of a value using modern PHP type names and full class names.get_defined_varsReturns an array of all variables defined in the current scope, keyed by variable name.gettypeReturns a string naming the type of a variable, using PHP's legacy type names.intvalConverts a value to an integer, optionally interpreting a string in another base.is_arrayChecks whether a variable is an array.is_boolChecks whether a variable is of type bool, without any truthiness conversion.is_callableChecks whether a value can be called as a function in the current scope.is_countableChecks whether a value can be passed to count() — an array or a Countable object.is_floatChecks whether a variable is of type float, without converting numeric strings.is_intChecks whether a variable is of type int, without converting numeric strings.is_iterableChecks whether a value can be used in foreach — an array or a Traversable object.is_nullChecks whether a variable holds null, returning true only for the null value itself.is_numericChecks whether a value is a number or a numeric string that PHP can safely use as one.is_objectChecks whether a variable holds an object instance of any class.is_scalarChecks whether a value is a simple int, float, string or bool rather than a structure.is_stringChecks whether a variable is of type string, without any type juggling.issetChecks whether one or more variables are declared and hold a value other than null.emptyChecks whether a variable is missing or holds a falsy value such as 0, "", null or [].unsetDestroys one or more variables, array elements or object properties in the current scope.print_rPrints a human-readable representation of any value, or returns it as a string.serializeConverts any PHP value except resources into a storable byte-stream string.settypeConverts a variable in place to a given type, changing the original variable by reference.strvalConverts any scalar value, null, or object with __toString() into a string.unserializeRebuilds a PHP value from a string produced by serialize().var_dumpPrints the type and value of one or more expressions in a readable, recursive format.var_exportOutputs or returns a variable as valid, parsable PHP code.is_resourceChecks whether a variable is an open resource handle such as a stream or context.get_resource_idReturns the unique integer identifier of a resource handle.debug_zval_dumpDumps a variable together with its internal reference count and storage details.
Multibyte String Functions32
mb_check_encodingChecks whether a string or array contains only byte sequences that are valid in a given encoding.mb_chrReturns the character for a given Unicode code point, encoded in the requested character encoding.mb_convert_caseConverts a string to upper, lower, title or folded case using full Unicode case mapping.mb_convert_encodingConverts a string or array of strings from one character encoding to another.mb_detect_encodingGuesses which character encoding a string is in, from a list of candidate encodings.mb_internal_encodingGets or sets the default character encoding used by the mbstring functions.mb_lcfirstLowercases the first character of a string using Unicode case mapping, leaving the rest unchanged.mb_list_encodingsReturns an array of every character encoding name supported by the mbstring extension.mb_ltrimStrips whitespace or a given set of characters from the start of a string, multibyte safely.mb_ordReturns the Unicode code point of the first character of a string.mb_rtrimStrips whitespace or a given set of characters from the end of a string, multibyte safely.mb_scrubReplaces every invalid byte sequence in a string with the configured substitute character.mb_splitSplits a multibyte string into an array using a multibyte-aware regular expression pattern.mb_str_padPads a string to a given length in characters, counting multibyte characters as one.mb_str_splitSplits a string into an array of characters or fixed-size chunks without breaking multibyte characters.mb_strcutExtracts a substring by byte offset and byte length without splitting a multibyte character.mb_strimwidthTruncates a string to a given display width, optionally appending an ellipsis marker.mb_striposFinds the character position of the first case-insensitive match of a substring in a string.mb_stristrReturns the part of a string from the first case-insensitive match of a substring onward.mb_strlenCounts the number of characters in a string for a given encoding, not the number of bytes.mb_strposFinds the character position of the first occurrence of a substring in a multibyte string.mb_strrchrReturns the part of a string from the last occurrence of a substring onward.mb_strriposFinds the character position of the last case-insensitive match of a substring in a string.mb_strrposFinds the character position of the last occurrence of a substring in a multibyte string.mb_strstrFinds the first occurrence of a substring and returns the rest of the string from that point.mb_strtolowerConverts all alphabetic characters in a string to lowercase using Unicode case rules.mb_strtoupperConverts all alphabetic characters in a string to uppercase using Unicode case rules.mb_strwidthReturns the display width of a string, counting fullwidth characters as two columns.mb_substrExtracts part of a string by character position, safely for multibyte encodings.mb_substr_countCounts how many non-overlapping times a substring occurs in a string.mb_trimStrips whitespace, including Unicode spaces, from both ends of a string.mb_ucfirstTitle-cases the first character of a string using Unicode rules, leaving the rest unchanged.
Class & Object Functions25
class_aliasCreates a second, fully interchangeable name for an existing class at runtime.class_existsChecks whether a class is defined, optionally triggering the autoloader to load it.enum_existsChecks whether the given name is a defined enum, optionally triggering the autoloader.get_called_classReturns the name of the class a static method was actually called on (late static binding).get_classReturns the name of the class an object is an instance of.get_class_methodsReturns the names of the methods a class defines that are visible from the calling scope.get_class_varsReturns a class's declared properties and their default values, without creating an instance.get_declared_classesReturns the names of every class currently defined in the running script.get_declared_interfacesReturns the names of every interface currently defined in the running script.get_declared_traitsReturns the names of every trait currently defined in the running script.get_mangled_object_varsReturns all of an object's properties using the engine's internal mangled key names.get_object_varsReturns an object's accessible non-static properties as a name-to-value associative array.get_parent_classReturns the name of the parent class of an object or class name, or false when there is no parent.interface_existsChecks whether an interface with the given name is defined, optionally running autoloaders first.is_aChecks whether an object or class name is of a given type, or has it as a parent or interface.is_subclass_ofChecks whether an object or class descends from a given class or implements a given interface.method_existsChecks whether a named method is defined on a given object or class.property_existsChecks whether a named property is declared on a class or set on an object, even when its value is null.trait_existsChecks whether a trait with the given name is defined, optionally running autoloaders first.spl_object_hashReturns a unique string identifier for an object, usable as an array key while the object is alive.spl_object_idReturns a unique integer identifier for an object, stable for as long as that object exists.spl_autoload_registerRegisters a callback that PHP runs to load a class, interface, trait or enum the first time it is used.iterator_to_arrayCopies the elements of an iterator or generator into a plain PHP array.iterator_countCounts the elements in an iterator or generator by traversing it to the end.iterator_applyCalls a callback for every element of a Traversable and returns how many iterations ran.
Hashing & Password Functions18
md5Calculates the MD5 message digest of a string and returns it as 32 hexadecimal characters.sha1Calculates the SHA-1 digest of a string and returns it as 40 hexadecimal characters.crc32Calculates the CRC-32 checksum of a string and returns it as an integer.hashGenerates a message digest of a string using any algorithm supported by the hash extension.hash_algosReturns a list of every hashing algorithm the current PHP build supports.hash_equalsCompares two strings in constant time so the comparison cannot leak information through timing.hash_fileCalculates the message digest of a file's contents using the chosen hashing algorithm.hash_hmacGenerates a keyed hash message authentication code using a shared secret and the chosen algorithm.hash_hmac_algosReturns the list of hashing algorithms that are valid for use with hash_hmac.md5_fileCalculates the MD5 digest of a file's contents without loading the whole file into memory.sha1_fileCalculates the SHA-1 digest of a file's contents without loading the whole file into memory.cryptHashes a string one-way using a salt that selects the algorithm, such as bcrypt or SHA-512.password_algosReturns the IDs of every password hashing algorithm available in the current PHP build.password_get_infoReturns the algorithm, name and options recorded inside a hash created by password_hash.password_hashCreates a secure, salted one-way hash of a password using bcrypt or Argon2.password_needs_rehashChecks whether a stored hash was made with a different algorithm or options than you now want.password_verifyChecks whether a plain-text password matches a hash created by password_hash.uniqidGenerates a 13- or 23-character time-based identifier, optionally with a prefix.
Regular Expression Functions11
preg_filterRuns a regex replacement over subjects and returns only the ones that actually matched.preg_grepReturns the array elements that match a regular expression, keeping their original keys.preg_last_errorReturns the error code from the most recent PCRE regex execution.preg_last_error_msgReturns a human-readable message for the last PCRE regex error.preg_matchSearches a string for the first match of a regular expression and captures the groups.preg_match_allFinds every match of a regular expression in a string and collects all captured groups.preg_quoteEscapes regular expression special characters so a string can be used literally in a pattern.preg_replaceReplaces every part of a string that matches a regular expression with a replacement.preg_replace_callbackReplaces regex matches using the string returned by a callback for each match.preg_replace_callback_arrayApplies several regex patterns, each with its own callback, to a subject in one call.preg_splitSplits a string into an array using a regular expression as the delimiter.
JSON Functions5
json_decodeParses a JSON string and returns it as a PHP object, array, or scalar value.json_encodeConverts a PHP value into its JSON string representation.json_last_errorReturns an integer error code describing why the last JSON encode, decode or validate call failed.json_last_error_msgReturns a human-readable message describing the last JSON encode, decode or validate error.json_validateChecks whether a string contains syntactically valid JSON without building the decoded value.
URL & Encoding Functions10
base64_decodeDecodes a MIME base64-encoded string back into its original bytes.base64_encodeEncodes binary or text data as an ASCII-safe MIME base64 string.http_build_queryBuilds a URL-encoded query string from an array or object of parameters.parse_urlSplits a URL into its scheme, host, port, path, query and fragment components.rawurldecodeDecodes percent-encoded sequences in a string, leaving plus signs untouched.rawurlencodePercent-encodes a string according to RFC 3986, encoding spaces as %20.urldecodeDecodes a URL-encoded string, converting plus signs back into spaces.urlencodeURL-encodes a string the way an HTML form does, turning spaces into plus signs.get_headersFetches the HTTP response headers sent by a server for the given URL.get_meta_tagsExtracts the name and content of every meta tag in an HTML document's head.
Character Type Functions11
ctype_alnumChecks whether every character in a string is a letter or a digit.ctype_alphaChecks whether every character in a string is a letter.ctype_cntrlChecks whether every character in a string is a control character such as tab, newline or escape.ctype_digitChecks whether every character in a string is a decimal digit.ctype_graphChecks whether every character in a string is printable and visible, with no whitespace.ctype_lowerChecks whether every character in a string is a lowercase letter.ctype_printChecks whether every character in a string is printable, including the space character.ctype_punctChecks whether every character in a string is printable punctuation, not a letter, digit or space.ctype_spaceChecks whether every character in a string is whitespace, such as a space, tab or newline.ctype_upperChecks whether every character in a string is an uppercase letter.ctype_xdigitChecks whether every character in a string is a valid hexadecimal digit.
Output Control Functions14
flushFlushes PHP's system write buffers and the backing web server buffer so output reaches the client now.ob_cleanErases the contents of the active output buffer while leaving the buffer open.ob_end_cleanDiscards the contents of the active output buffer and turns that buffer off.ob_end_flushSends the active output buffer's contents onward and turns that buffer off.ob_flushSends the current contents of the active output buffer onward and leaves the buffer open.ob_get_cleanReturns the contents of the active output buffer as a string and turns the buffer off.ob_get_contentsReturns the current contents of the output buffer without emptying or closing it.ob_get_flushSends the active output buffer, returns its contents as a string, and turns the buffer off.ob_get_lengthReturns the number of bytes currently held in the active output buffer.ob_get_levelReturns how many output buffers are currently nested, or zero when buffering is not active.ob_get_statusReturns status information about the top output buffer, or about every active buffer level.ob_implicit_flushTurns implicit flushing on or off so output is flushed after every block of code that produces output.ob_list_handlersReturns the names of the output handlers currently in use, from the outermost buffer inwards.ob_startTurns on output buffering so echoed output is held in memory instead of being sent immediately.
Error Handling Functions13
debug_backtraceReturns the current PHP call stack as an array of frames without halting execution.debug_print_backtracePrints the current PHP call stack straight to the output for quick debugging.error_clear_lastClears the most recent error so that error_get_last() reports null again.error_get_lastReturns details of the most recent PHP error as an array, or null if none occurred.error_logSends an error message to the server log, a specific file, a SAPI handler, or an email address.error_reportingSets which error levels PHP reports and returns the level that was in effect before.get_error_handlerReturns the callable currently registered as the error handler, or null for the built-in one.get_exception_handlerReturns the callable currently registered as the exception handler, or null if none is set.restore_error_handlerPops the most recent error handler off the stack and reactivates the previous one.restore_exception_handlerRestores the exception handler that was active before the last set_exception_handler() call.set_error_handlerRegisters a user function to handle PHP errors instead of the built-in handler.set_exception_handlerRegisters a function to run when an exception escapes every try/catch block.trigger_errorRaises a user-level error, warning, notice or deprecation that PHP's error handling picks up.
Miscellaneous Functions20
constantReturns the value of a constant whose name is given as a string at runtime.defineDefines a named constant at runtime that cannot be changed or unset afterwards.definedChecks whether a constant, class constant or enum case with the given name exists.dieTerminates the script immediately, optionally printing a message or setting an exit code.exitEnds script execution immediately, printing a message or returning a status code to the caller.evalEvaluates a string as PHP code in the current variable scope and returns its result.packPacks values into a binary string according to a format of type codes and repeaters.unpackUnpacks a binary string into an array of PHP values using a format of type codes.sleepPauses execution of the current script for the given whole number of seconds.time_nanosleepDelays execution for a given number of seconds and nanoseconds, reporting time left if interrupted.php_strip_whitespaceReturns the source of a PHP file with all comments and unnecessary whitespace removed.highlight_stringOutputs or returns HTML markup showing the given PHP code with syntax highlighting.version_compareCompares two PHP-style version number strings and reports which one is newer.php_sapi_nameReturns the lowercase name of the server API (SAPI) that PHP is currently running under.memory_get_usageReturns the number of bytes of memory currently allocated to the running PHP script.memory_get_peak_usageReturns the highest number of bytes of memory the script has held at any point so far.gc_collect_cyclesForces PHP's cycle collector to run immediately and returns how many cycles it freed.getenvReads the value of one environment variable, or returns all of them as an array.set_time_limitSets how many seconds the script may keep running and restarts the timeout counter from zero.assertChecks that a condition holds and raises an AssertionError when it does not.
Filter & Validation Functions7
filter_has_varChecks whether a variable was actually sent in the given input type, such as GET, POST or COOKIE.filter_idReturns the numeric filter ID for a filter's name, or false when no filter goes by that name.filter_inputReads one variable from GET, POST, COOKIE, SERVER or ENV and validates or sanitizes it in one step.filter_input_arrayReads and filters many request variables at once from GET, POST, COOKIE, SERVER or ENV.filter_listReturns the names of every filter this PHP build supports, as an array of strings.filter_varValidates or sanitizes a single value with a built-in filter, returning false when it fails.filter_var_arrayFilters many values in an array at once against a per-key set of validation or sanitization rules.
Function Handling11
call_user_funcCalls a callable given by name, array or closure and returns whatever it returns.call_user_func_arrayCalls a callable with its arguments supplied as an array, positional or named.forward_static_callCalls a callable from inside a class while preserving the current late static binding class.forward_static_call_arrayCalls a callable with an array of arguments while preserving the current called class.func_get_argReturns a single argument passed to the current function, selected by zero-based position.func_get_argsReturns all arguments passed to the current function as a numerically indexed array.func_num_argsReturns how many arguments were actually passed to the current function.function_existsReturns true when a function with the given name has been defined and is available.get_defined_functionsReturns every defined function name, split into internal and user-defined lists.register_shutdown_functionRegisters a callback that PHP runs when the script finishes or exit() is called.usleepPauses script execution for the given number of microseconds.
All PHP reference pages A–Z
A
array_change_key_casearray_chunkarray_columnarray_combinearray_count_valuesarray_diffarray_diff_assocarray_diff_keyarray_diff_uassocarray_diff_ukeyarray_fillarray_fill_keysarray_filterarray_fliparray_intersectarray_intersect_assocarray_intersect_keyarray_intersect_uassocarray_intersect_ukeyarray_is_listarray_key_existsarray_key_firstarray_key_lastarray_keysarray_maparray_mergearray_merge_recursivearray_multisortarray_padarray_poparray_productarray_pusharray_randarray_reducearray_replacearray_replace_recursivearray_reversearray_searcharray_shiftarray_slicearray_splicearray_sumarray_udiffarray_udiff_assocarray_uintersectarray_uniquearray_unshiftarray_valuesarray_walkarray_walk_recursivearsortasortarray_allarray_anyarray_findarray_find_keyarray_firstarray_lastaddslashesaddcslashesabsacosacoshasinasinhatanatan2atanhassert
C
D
E
F
fdivfloorfmodfpowfclosefeoffflushfgetcfgetcsvfgetsfilefile_existsfile_get_contentsfile_put_contentsfileatimefilemtimefilepermsfilesizefiletypeflockfnmatchfopenfpassthrufputcsvfreadfscanffseekfstatftellftruncatefwritefputsfdatasyncfsyncfloatvalflushfilter_has_varfilter_idfilter_inputfilter_input_arrayfilter_listfilter_varfilter_var_arrayforward_static_callforward_static_call_arrayfunc_get_argfunc_get_argsfunc_num_argsfunction_exists
G
get_html_translation_tablegetrandmaxgetdategettimeofdaygmdategmmktimeglobget_debug_typeget_defined_varsgettypeget_resource_idget_called_classget_classget_class_methodsget_class_varsget_declared_classesget_declared_interfacesget_declared_traitsget_mangled_object_varsget_object_varsget_parent_classget_headersget_meta_tagsget_error_handlerget_exception_handlergc_collect_cyclesgetenvget_defined_functions
H
I
in_arrayimplodeintdivis_finiteis_infiniteis_nanidateis_diris_executableis_fileis_linkis_readableis_uploaded_fileis_writableintvalis_arrayis_boolis_callableis_countableis_floatis_intis_iterableis_nullis_numericis_objectis_scalaris_stringissetis_resourceinterface_existsis_ais_subclass_ofiterator_to_arrayiterator_countiterator_apply
M
metaphonemoney_formatmaxminmt_randmt_srandmt_getrandmaxmicrotimemktimemkdirmove_uploaded_filemb_check_encodingmb_chrmb_convert_casemb_convert_encodingmb_detect_encodingmb_internal_encodingmb_lcfirstmb_list_encodingsmb_ltrimmb_ordmb_rtrimmb_scrubmb_splitmb_str_padmb_str_splitmb_strcutmb_strimwidthmb_striposmb_stristrmb_strlenmb_strposmb_strrchrmb_strriposmb_strrposmb_strstrmb_strtolowermb_strtouppermb_strwidthmb_substrmb_substr_countmb_trimmb_ucfirstmethod_existsmd5md5_filememory_get_usagememory_get_peak_usage
O
P
prevparse_strprintfpipowparse_ini_fileparse_ini_stringpathinfoprint_rproperty_existspassword_algospassword_get_infopassword_hashpassword_needs_rehashpassword_verifypreg_filterpreg_greppreg_last_errorpreg_last_error_msgpreg_matchpreg_match_allpreg_quotepreg_replacepreg_replace_callbackpreg_replace_callback_arraypreg_splitparse_urlpackphp_strip_whitespacephp_sapi_name
R
S
shufflesortsizeofsimilar_textsoundexsprintfsscanfstr_containsstr_decrementstr_ends_withstr_getcsvstr_incrementstr_ireplacestr_padstr_repeatstr_replacestr_rot13str_shufflestr_splitstr_starts_withstr_word_countstrcasecmpstrcmpstrcspnstrip_tagsstripslashesstriposstristrstrlenstrnatcasecmpstrnatcmpstrncasecmpstrncmpstrpbrkstrposstrrchrstrrevstrriposstrrposstrspnstrstrstrtokstrtolowerstrtoupperstrtrsubstrsubstr_comparesubstr_countsubstr_replacestripcslashessinsinhsqrtsrandstrtotimestrftimestatserializesettypestrvalspl_object_hashspl_object_idspl_autoload_registersha1sha1_fileset_error_handlerset_exception_handlersleepset_time_limit