PHP Cheat Sheet: Functions, Constants & Reference Guide

PHP (Hypertext Preprocessor) remains one of the most widely used server-side languages in web development, powering everything from small personal sites to large-scale platforms. Whether you are new to the language or an experienced developer who needs a quick reference guide while building, this PHP cheat sheet covers every major built-in function, constant, and language construct organized by category.

This reference guide covers PHP 8.x syntax and functions. Functions deprecated or removed in PHP 8 are flagged inline.

If you are just getting started, this guide is built for beginners and experienced developers alike. Jump to any section using the table of contents below.

Table of Contents

PHP Syntax Quick Reference

This section covers the core language syntax every PHP developer needs. If you are working through a tutorial or building your first project, these are the constructs you will use constantly. And here's a PDF you can copy. It's the at-a-glance cheat sheet for PHP.

Variables and Data Types

In PHP, every variable starts with a dollar sign ($). Variable names are case-sensitive, must begin with a letter or underscore, and can contain only alphanumeric characters and underscores.


$name = "Jane";          // String
$age = 30;               // Integer
$price = 9.99;           // Float
$active = true;          // Boolean
$nothing = null;         // Null

A global variable declared outside a function is not automatically available inside functions. Use the global keyword to access it:


$count = 0;

function increment() {
    global $count;
    $count++;
}

Comments


// Single-line comment
# Also a single-line comment

/* 
   Multi-line comments span
   multiple lines like this
*/

Multi-line comments are useful for documenting functions, classes, and complex logic blocks.

Strings and Escape Characters


$greeting = "Hello, World!";
$multiline = "Line one\nLine two";   // \n = newline
$tab = "Column1\tColumn2";           // \t = tab
$quote = "She said \"hello\"";       // \" = escaped quote
$dollar = "Cost: \$10";              // \$ = literal dollar sign

Common escape characters in PHP double-quoted strings:

Escape Sequence Meaning
\n Newline
\t Tab
\r Carriage return
\\ Backslash
\$ Dollar sign literal
\" Double quote

Operators

Operator Type Example
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b
/ Division $a / $b
% Modulus $a % $b
** Exponentiation $a ** $b
== Equal $a == $b
=== Identical (type + value) $a === $b
!= Not equal $a != $b
< Less than $a < $b
> Greater than $a > $b
&& Logical AND $a && $b
|| Logical OR $a || $b
! Logical NOT !$a
++ Increment $a++ or ++$a
-- Decrement $a-- or --$a
.= String concatenation assign $a .= $b

Control Flow


// if / elseif / else
if ($score >= 90) {
    echo "A";
} elseif ($score >= 80) {
    echo "B";
} else {
    echo "C";
}

// switch statement
switch ($day) {
    case "Mon":
        echo "Monday";
        break;
    case "Tue":
        echo "Tuesday";
        break;
    default:
        echo "Other day";
}

// match expression (PHP 8+)
$label = match($status) {
    1 => "Active",
    2 => "Inactive",
    default => "Unknown"
};

The switch statement evaluates a single value against multiple cases. For more concise value matching in PHP 8, use match(), which is strict (uses === comparison) and returns a value directly.

Loops

PHP supports four loop types. The foreach loop is the most common when working with arrays, iterating over each value in sequence.


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

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

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

// foreach loop (value iteration over arrays)
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo $color;
}

// foreach with key => value
$person = ["name" => "Jane", "age" => 30];
foreach ($person as $key => $value) {
    echo "$key: $value";
}

The foreach loop is the standard approach for value iteration in PHP. It works with both indexed arrays (numeric index) and associative arrays (string keys). When looping in PHP over multidimensional arrays, nest foreach loops to access inner elements.

Functions


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

// Default parameter value
function greet($name = "World") {
    return "Hello, $name!";
}

// Type declarations (PHP 7+)
function add(int $a, int $b): int {
    return $a + $b;
}

// Anonymous function
$square = function($n) {
    return $n * $n;
};

// Arrow function (PHP 7.4+)
$square = fn($n) => $n * $n;

Object-Oriented Syntax Overview

PHP supports full OOP including classes, interfaces, traits, and inheritance. Here is a quick reference before the detailed magic methods section below.


// Class with constructor and public function
class Animal {
    public string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function speak(): string {
        return "{$this->name} makes a sound.";
    }
}

// Inheritance
class Dog extends Animal {
    public function speak(): string {
        return "{$this->name} barks.";
    }
}

// Interface
interface Runnable {
    public function run(): void;
}

// Trait
trait Logger {
    public function log(string $msg): void {
        echo "[LOG] $msg";
    }
}

// Using interface + trait
class Robot implements Runnable {
    use Logger;

    public function run(): void {
        $this->log("Running...");
    }
}

Interfaces define contracts that classes must fulfill. Traits allow horizontal code reuse across classes that do not share a parent. Inheritance lets a child class extend a parent and override its methods. Together these form the backbone of structured PHP applications.

Arrays Quick Reference


// Indexed array
$arr = ["apple", "banana", "cherry"];
echo $arr[0]; // apple

// Associative array
$person = ["name" => "Jane", "age" => 30];
echo $person["name"]; // Jane

// Multidimensional arrays
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
echo $matrix[1][2]; // 6

// Common array operations
$arr[] = "new item";              // Append
array_push($arr, "another");      // Push to end
$last = array_pop($arr);          // Remove from end
$count = count($arr);             // Count elements
sort($arr);                       // Sort ascending

User Input and Sanitization

Handling user input safely is critical in any web application. Always sanitize and validate before using input in your logic or database queries.


// GET and POST input
$name = $_GET["name"] ?? "";
$email = $_POST["email"] ?? "";

// Sanitize user input
$clean = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);

// Validate
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email";
}

// Prevent SQL injection with prepared statements
$stmt = $mysqli->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $clean);
$stmt->execute();

PHP 8.x New Features (Quick Reference)

Feature PHP Version Example
str_contains() PHP 8.0 str_contains($str, "foo")
str_starts_with() PHP 8.0 str_starts_with($str, "foo")
str_ends_with() PHP 8.0 str_ends_with($str, "foo")
match expression PHP 8.0 match($val) { 1 => "one" }
Named arguments PHP 8.0 array_slice(array: $arr, offset: 1)
Nullsafe operator PHP 8.0 $obj?->method()
Enums PHP 8.1 enum Status { case Active; }
Readonly properties PHP 8.1 public readonly string $name;
Fibers PHP 8.1 Cooperative multitasking
Readonly classes PHP 8.2 readonly class Point {}
Typed class constants PHP 8.3 const string VERSION = "1.0";

Variable Handling Functions

Variables in PHP are containers for storing data. Every variable name is preceded with a dollar sign and is case-sensitive. Variable handling functions allow you to define, inspect, and manipulate variables at runtime.

  • A variable name must start with a letter or an underscore
  • A variable cannot start with a number
  • A variable can only contain alphanumeric characters and underscores
  • $Result and $result are treated as two different variables
# Function Description
1 boolval Returns the boolean value of a variable.
2 debug_zval_dump Dumps the string representation of an internal zend value to output.
3 doubleval Alias of floatval.
4 empty Determines whether a variable is empty.
5 floatval Returns the float value of a variable.
6 get_defined_vars Returns an array of all defined variables.
7 get_resource_type Returns the resource type.
8 gettype Returns the type of a variable.
9 import_request_variables Imports GET/POST/Cookie variables. Removed in PHP 5.4.
10 intval Gets the integer value of a variable.
11 is_array Determines whether the variable is an array.
12 is_bool Determines whether a variable is boolean.
13 is_callable Verifies if the contents of a variable can be called as a function.
14 is_float | is_double | is_real Determines whether the type of a variable is float.
15 is_int | is_integer | is_long Determines whether the type of a variable is an integer.
16 is_null Determines whether a variable is NULL.
17 is_numeric Determines whether a variable is a number or a numeric string.
18 is_object Determines whether a variable is an object.
19 is_resource Determines whether a variable is a resource.
20 is_scalar Determines whether a variable is scalar.
21 is_string Determines whether the type of a variable is string.
22 isset Determines if a variable is set and not NULL.
23 print_r Prints human readable info about a variable.
24 serialize Generates a storable representation of a value.
25 settype Sets the type of a variable.
26 strval Gets the string value of a variable.
27 unserialize Creates a PHP value from a stored representation.
28 unset Unsets a given variable.
29 var_dump Dumps information about a variable.
30 var_export Outputs or returns a parsable string representation of a variable.

Array Functions

An array stores a list of values in a single variable. Values in an indexed array are accessed by a numeric index starting at 0. PHP supports three types of arrays:

  • Indexed: Default format. Values accessed by numeric index.
  • Associative: Use named string keys instead of a numeric index.
  • Multidimensional: Arrays that contain one or more arrays, allowing matrix-style data structures.

When working with multidimensional arrays, you typically nest a foreach loop inside another to iterate through inner arrays. Array built-in functions cover everything from sorting and searching to merging and filtering.

# Function Description
1 array() Declares and creates an array.
2 array_change_key_case() Returns an array with all keys in lowercase or uppercase.
3 array_chunk() Splits an array into chunks.
4 array_combine() Creates an array using one array for keys and one for values.
5 array_count_values() Returns an array with the number of occurrences for each value.
6 array_diff() Compares array values and returns the differences.
7 array_diff_assoc() Compares array keys and values and returns the differences.
8 array_diff_key() Compares array keys and returns the differences.
9 array_diff_uassoc() Compares array keys and values with an additional user-defined function check and returns the differences.
10 array_diff_ukey() Compares array keys with an additional user-defined function check and returns the differences.
11 array_fill() Fills an array with values.
12 array_filter() Filters elements of an array through a user-defined function.
13 array_flip() Exchanges all keys with their associated values in the array.
14 array_intersect() Compares array values and returns the matches.
15 array_intersect_assoc() Compares array keys and values and returns the matches.
16 array_intersect_key() Compares array keys and returns the matches.
17 array_intersect_uassoc() Compares keys and values with an additional user-defined function check and returns the matches.
18 array_intersect_ukey() Compares keys with an additional user-defined function check and returns the matches.
19 array_key_exists() Determines if a specified key exists in the array.
20 array_keys() Returns all keys of an array.
21 array_map() Sends each value of an array to a user-defined function which returns new values.
22 array_merge() | array_merge_recursive() Merges one or more arrays into one array.
23 array_multisort() Sorts multiple or multidimensional arrays.
24 array_pad() Inserts a specified number of items with a specified value into an array.
25 array_pop() Deletes the last element of an array.
26 array_product() Calculates the product of the values in an array.
27 array_push() Inserts one or more elements to the end of an array.
28 array_rand() Returns one or more random keys from an array.
29 array_reduce() Returns an array reduced to a string using a user-defined function.
30 array_reverse() Returns an array in reverse order.
31 array_search() Searches an array for a given value and returns the key.
32 array_shift() Removes the first element from an array and returns its value.
33 array_slice() Returns a slice of an array.
34 array_splice() Removes and replaces specified elements of an array.
35 array_sum() Returns the sum of the values in an array.
36 array_udiff() Compares array values in a user-defined function and returns an array.
37 array_udiff_assoc() Compares array keys and values in a user-defined function and returns an array.
38 array_udiff_uassoc() Compares array keys and values in user-defined functions and returns an array.
39 array_uintersect() Compares array values in a user-defined function and returns an array.
40 array_uintersect_assoc() Compares array keys and values in a user-defined function and returns an array.
41 array_uintersect_uassoc() Compares array keys and values in user-defined functions and returns an array.
42 array_unique() Removes duplicate values from an array.
43 array_unshift() Adds one or more elements to the beginning of an array.
44 array_values() Returns all the values of an array.
45 array_walk() Applies a user function to every member of an array.
46 array_walk_recursive() Applies a user function recursively to every member of an array.
47 arsort() Sorts an array in reverse order and maintains index association.
48 asort() Sorts an array and maintains index association.
49 compact() Creates an array containing variables and their values.
50 count() Counts elements in an array or properties in an object.
51 current() Returns the current element in an array.
52 each() Returns the current key and value pair from an array. Removed in PHP 8.0.
53 end() Sets the internal pointer of an array to its last element.
54 extract() Imports variables into the current symbol table from an array.
55 in_array() Checks if a specified value exists in an array.
56 key() Fetches a key from an array.
57 krsort() Sorts an array by key in reverse order.
58 ksort() Sorts an array by key.
59 list() Assigns variables as if they were an array.
60 natcasesort() Sorts an array using a case-insensitive natural order algorithm.
61 natsort() Sorts an array using a natural order algorithm.
62 next() Advances the internal array pointer.
63 pos() Alias of current().
64 prev() Rewinds the internal array pointer.
65 range() Creates an array containing a range of elements.
66 reset() Sets the internal pointer of an array to its first element.
67 rsort() Sorts an array in reverse order.
68 shuffle() Shuffles an array.
69 sizeof() Alias of count().
70 sort() Sorts an array.
71 uasort() Sorts an array with a user-defined function and maintains index association.
72 uksort() Sorts an array by keys using a user-defined function.
73 usort() Sorts an array by values using a user-defined function.

Array Constants

# Constant Description
1 CASE_LOWER Used with array_change_key_case() to convert array keys to lowercase.
2 CASE_UPPER Used with array_change_key_case() to convert array keys to uppercase.
3 SORT_ASC Used with array_multisort() to sort in ascending order.
4 SORT_DESC Used with array_multisort() to sort in descending order.
5 SORT_REGULAR Used to compare items normally.
6 SORT_NUMERIC Used to compare items numerically.
7 SORT_STRING Used to compare items as strings.
8 SORT_LOCALE_STRING Used to compare items as strings based on the current locale.
9 COUNT_NORMAL Counts all elements in an array.
10 COUNT_RECURSIVE Recursively counts the elements in an array.
11 EXTR_OVERWRITE Imports variables from an array into the current symbol table, overwriting on collision.
12 EXTR_SKIP On collision, does not overwrite the existing variable.
13 EXTR_PREFIX_SAME On collision, prefixes the variable name with prefix.
14 EXTR_PREFIX_ALL Prefixes all variable names with prefix.
15 EXTR_PREFIX_INVALID Only prefixes invalid or numeric variable names with prefix.
16 EXTR_PREFIX_IF_EXISTS Only creates prefixed variable names if the non-prefixed version already exists in the symbol table.
17 EXTR_IF_EXISTS Only overwrites the variable if it already exists in the current symbol table. Useful for extracting only known variables from $_REQUEST.
18 EXTR_REFS Extracts variables as references. The imported variable values remain references to the original array values.

String Functions

Strings are sequences of characters and one of the most commonly used data types in PHP. String built-in functions handle everything from searching and replacing to encoding and binary safe string comparison between two values at a specified offset.

# Function Description
1 addcslashes() Returns a string with backslashes in front of specified characters.
2 addslashes() Returns a string with backslashes in front of predefined characters.
3 bin2hex() Converts a string of ASCII characters to hexadecimal values.
4 chop() Alias of rtrim().
5 chr() Returns a character from a specified ASCII value.
6 chunk_split() Splits a string into a series of smaller parts.
7 convert_cyr_string() Converts a string from one Cyrillic character set to another.
8 convert_uudecode() Decodes a uuencoded string.
9 convert_uuencode() Encodes a string using the uuencode algorithm.
10 count_chars() Returns information about how many times each ASCII character occurs within a string.
11 crc32() Calculates a 32-bit CRC for a string.
12 crypt() One-way string hashing. Use password_hash() for new code.
13 echo() Outputs one or more strings.
14 explode() Breaks a string into an array.
15 fprintf() Writes a formatted string to a specified output stream.
16 get_html_translation_table() Returns the translation table used by htmlspecialchars() and htmlentities().
17 hebrev() Converts Hebrew text to visual text.
18 hebrevc() Converts Hebrew text to visual text and newlines to <br/>.
19 html_entity_decode() Converts HTML entities to characters.
20 htmlentities() Converts characters to HTML entities.
21 htmlspecialchars_decode() Converts predefined HTML entities to characters.
22 htmlspecialchars() Converts predefined characters to HTML entities.
23 implode() Returns a string from the elements of an array.
24 join() Alias of implode().
25 levenshtein() Returns the Levenshtein distance between two strings.
26 localeconv() Returns locale numeric and monetary formatting information.
27 ltrim() Strips whitespace from the left side of a string.
28 md5() Calculates the MD5 hash of a string.
29 md5_file() Calculates the MD5 hash of a file.
30 metaphone() Calculates the metaphone key of a string.
31 money_format() Returns a string formatted as a currency string. Removed in PHP 8.0. Use NumberFormatter instead.
32 nl_langinfo() Returns specific locale information.
33 nl2br() Inserts HTML line breaks before each newline in a string.
34 number_format() Formats a number with grouped thousands.
35 ord() Returns the ASCII value of the first character of a string.
36 parse_str() Parses a query string into variables.
37 print() Outputs a string.
38 printf() Outputs a formatted string.
39 quoted_printable_decode() Decodes a quoted-printable string.
40 quotemeta() Quotes meta-characters.
41 rtrim() Strips whitespace from the right side of a string.
42 setlocale() Sets locale information.
43 sha1() Calculates the SHA-1 hash of a string.
44 sha1_file() Calculates the SHA-1 hash of a file.
45 similar_text() Calculates the similarity between two strings.
46 soundex() Calculates the soundex key of a string.
47 sprintf() Writes a formatted string to a variable.
48 sscanf() Parses input from a string according to a format.
49 str_contains() Checks if a string contains a given substring. PHP 8.0+.
50 str_ends_with() Checks if a string ends with a given substring. PHP 8.0+.
51 str_ireplace() Replaces characters in a string (case-insensitive).
52 str_pad() Pads a string to a new length.
53 str_repeat() Repeats a string a specified number of times.
54 str_replace() Replaces characters in a string (case-sensitive).
55 str_rot13() Performs ROT13 encoding on a string.
56 str_shuffle() Randomly shuffles all characters in a string.
57 str_split() Splits a string into an array.
58 str_starts_with() Checks if a string starts with a given substring. PHP 8.0+.
59 str_word_count() Counts the number of words in a string.
60 strcasecmp() Compares two strings (case-insensitive).
61 strchr() Finds the first occurrence of a string inside another string. Alias of strstr().
62 strcmp() Compares two strings (case-sensitive).
63 strcoll() Locale-based string comparison.
64 strcspn() Returns the number of characters found in a string before any part of a specified character list is found.
65 strip_tags() Strips HTML and PHP tags from a string.
66 stripcslashes() Unquotes a string quoted with addcslashes().
67 stripslashes() Unquotes a string quoted with addslashes().
68 stripos() Returns the position of the first occurrence of a string inside another string (case-insensitive).
69 stristr() Finds the first occurrence of a string inside another string (case-insensitive).
70 strlen() Returns the length of a string.
71 strnatcasecmp() Compares two strings using a case-insensitive natural order algorithm.
72 strnatcmp() Compares two strings using a natural order algorithm.
73 strncasecmp() Binary safe string comparison of the first n characters (case-insensitive).
74 strncmp() Binary safe string comparison of the first n characters (case-sensitive).
75 strpbrk() Searches a string for any character from a specified set.
76 strpos() Returns the position of the first occurrence of a string inside another string (case-sensitive).
77 strrchr() Finds the last occurrence of a string inside another string.
78 strrev() Reverses a string.
79 strripos() Finds the position of the last occurrence of a string inside another string (case-insensitive).
80 strrpos() Finds the position of the last occurrence of a string inside another string (case-sensitive).
81 strspn() Returns the number of characters found in a string that contains only characters from a specified character list.
82 strstr() Finds the first occurrence of a string inside another string (case-sensitive).
83 strtok() Splits a string into smaller strings.
84 strtolower() Converts a string to lowercase letters.
85 strtoupper() Converts a string to uppercase letters.
86 strtr() Translates certain characters in a string.
87 substr() Returns a part of a string.
88 substr_compare() Binary safe string comparison of two strings from a specified start position, optionally case-sensitive.
89 substr_count() Counts the number of times a substring occurs in a string.
90 substr_replace() Replaces part of a string with another string.
91 trim() Strips whitespace from both sides of a string.
92 ucfirst() Converts the first character of a string to uppercase.
93 ucwords() Converts the first character of each word in a string to uppercase.
94 vfprintf() Writes a formatted string to a specified output stream.
95 vprintf() Outputs a formatted string.
96 vsprintf() Writes a formatted string to a variable.
97 wordwrap() Wraps a string to a given number of characters.

String Constants

# Constant Description
1 CRYPT_SALT_LENGTH Contains the length of the default encryption method for the system. For standard DES encryption, the length is 2.
2 CRYPT_STD_DES Set to 1 if standard DES-based encryption with a 2-character salt is supported, 0 otherwise.
3 CRYPT_EXT_DES Set to 1 if extended DES-based encryption with a 9-character salt is supported, 0 otherwise.
4 CRYPT_MD5 Set to 1 if MD5 encryption with a 12-character salt starting with $1$ is supported, 0 otherwise.
5 CRYPT_BLOWFISH Set to 1 if Blowfish encryption with a 16-character salt starting with $2$ or $2a$ is supported, 0 otherwise.
6 HTML_SPECIALCHARS Converts predefined characters to HTML entities.
7 HTML_ENTITIES Converts special characters in an input string to HTML character entities.
8 ENT_COMPAT Converts double quotes.
9 ENT_QUOTES Converts both single and double quotes.
10 ENT_NOQUOTES Leaves both single and double quotes unconverted.
11 ENT_IGNORE Silently discards invalid code unit sequences. Discouraged due to security implications.
12 ENT_SUBSTITUTE Replaces invalid code unit sequences with a Unicode Replacement Character.
13 ENT_DISALLOWED Replaces invalid code points with a Unicode Replacement Character. Useful for ensuring well-formed XML documents.
14 ENT_HTML401 Handles code as HTML 4.01.
15 ENT_XML1 Handles code as XML 1.
16 ENT_XHTML Handles code as XHTML.
17 ENT_HTML5 Handles code as HTML 5.
18 CHAR_MAX If an array element equals CHAR_MAX, no further grouping is performed.
19 LC_CTYPE For character classification and conversion.
20 LC_NUMERIC Used for the decimal separator.
21 LC_TIME For date and time formatting.
22 LC_COLLATE For string comparison.
23 LC_MONETARY For localeconv().
24 LC_ALL For all LC_ functions.
25 LC_MESSAGES For system responses.
26 STR_PAD_LEFT Pads the left side of an input string.
27 STR_PAD_RIGHT Pads the right side of an input string.
28 STR_PAD_BOTH Pads both sides of an input string.

Math Functions

Math functions handle values within the range of integer and float types. Use these for calculations, rounding, random number generation, and number base conversions.

# Function Description
1 abs() Returns the absolute value of a number.
2 acos() Returns the arccosine of a number.
3 acosh() Returns the inverse hyperbolic cosine of a number.
4 asin() Returns the arcsine of a number.
5 asinh() Returns the inverse hyperbolic sine of a number.
6 atan() Returns the arctangent of a number as a value between -pi/2 and +pi/2 radians.
7 atan2() Returns the angle theta of an (x,y) point as a value between -pi and +pi radians.
8 atanh() Returns the inverse hyperbolic tangent of a number.
9 base_convert() Converts a number from one base to another.
10 bindec() Converts a binary number to a decimal number.
11 ceil() Returns the value of a number rounded upward to the nearest integer.
12 cos() Returns the cosine of a number.
13 cosh() Returns the hyperbolic cosine of a number.
14 decbin() Converts a decimal number to a binary number.
15 dechex() Converts a decimal number to a hexadecimal number.
16 decoct() Converts a decimal number to an octal number.
17 deg2rad() Converts degrees to radians.
18 exp() Returns e raised to the power of a number.
19 expm1() Returns exp(x) - 1, computed in a way that is accurate even when x is close to zero.
20 floor() Returns the value of a number rounded downward to the nearest integer.
21 fmod() Returns the floating-point remainder of a division.
22 getrandmax() Returns the maximum random number that can be returned by rand().
23 hexdec() Converts a hexadecimal number to a decimal number.
24 hypot() Returns the length of the hypotenuse of a right-angle triangle.
25 is_finite() Returns true if a value is a finite number.
26 is_infinite() Returns true if a value is an infinite number.
27 is_nan() Returns true if a value is not a number.
28 lcg_value() Returns a pseudo-random number in the range of (0,1).
29 log() Returns the natural logarithm (base E) of a number.
30 log10() Returns the base-10 logarithm of a number.
31 log1p() Returns log(1 + number).
32 max() Returns the highest value from two or more specified numbers.
33 min() Returns the lowest value from two or more specified numbers.
34 mt_getrandmax() Returns the largest possible value from mt_rand().
35 mt_rand() Returns a random integer using the Mersenne Twister algorithm.
36 mt_srand() Seeds the Mersenne Twister random number generator.
37 octdec() Converts an octal number to a decimal number.
38 pi() Returns the value of pi.
39 pow() Returns x to the power of y.
40 rad2deg() Converts radians to degrees.
41 rand() Returns a random integer.
42 round() Rounds a number to the nearest integer.
43 sin() Returns the sine of a number.
44 sinh() Returns the hyperbolic sine of a number.
45 sqrt() Returns the square root of a number.
46 srand() Seeds the random number generator.
47 tan() Returns the tangent of an angle.
48 tanh() Returns the hyperbolic tangent of an angle.

Math Constants

# Constant Description
1 M_E Returns e (approx. 2.718)
2 M_EULER Returns Euler's constant (approx. 0.577)
3 M_LNPI Returns the natural logarithm of PI (approx. 1.144)
4 M_LN2 Returns the natural logarithm of 2 (approx. 0.693)
5 M_LN10 Returns the natural logarithm of 10 (approx. 2.302)
6 M_LOG2E Returns the base-2 logarithm of E (approx. 1.442)
7 M_LOG10E Returns the base-10 logarithm of E (approx. 0.434)
8 M_PI Returns PI (approx. 3.14159)
9 M_PI_2 Returns PI/2 (approx. 1.570)
10 M_PI_4 Returns PI/4 (approx. 0.785)
11 M_1_PI Returns 1/PI (approx. 0.318)
12 M_2_PI Returns 2/PI (approx. 0.636)
13 M_SQRTPI Returns the square root of PI (approx. 1.772)
14 M_2_SQRTPI Returns 2 divided by the square root of PI (approx. 1.128)
15 M_SQRT1_2 Returns the square root of 1/2 (approx. 0.707)
16 M_SQRT2 Returns the square root of 2 (approx. 1.414)
17 M_SQRT3 Returns the square root of 3 (approx. 1.732)

Date/Time Functions

Date and time functions let you retrieve, format, and manipulate dates on the server running your PHP script.

# Function Description
1 checkdate() Validates a Gregorian date.
2 date_default_timezone_get() Returns the default time zone.
3 date_default_timezone_set() Sets the default time zone.
4 date_sunrise() Returns the time of sunrise for a given date and location.
5 date_sunset() Returns the time of sunset for a given date and location.
6 date() Formats a local date and time.
7 getdate() Returns an array containing date and time information for a Unix timestamp.
8 gettimeofday() Returns an array containing current time information.
9 gmdate() Formats a GMT/UTC date and time.
10 gmmktime() Returns the Unix timestamp for a GMT date.
11 gmstrftime() Formats a GMT/UTC date and time according to locale settings.
12 idate() Formats a local date and time as an integer.
13 localtime() Returns an array containing the time components of a Unix timestamp.
14 microtime() Returns the current Unix timestamp with microseconds.
15 mktime() Returns the Unix timestamp for a date.
16 strftime() Formats local date and time according to locale settings.
17 strptime() Parses a time/date generated with strftime().
18 strtotime() Parses an English textual datetime into a Unix timestamp.
19 time() Returns the current time as a Unix timestamp.

Date/Time Constants

# Constant Description
1 DATE_ATOM Atom format (example: 2005-08-15T16:13:03+0000)
2 DATE_COOKIE HTTP Cookies (example: Sun, 14 Aug 2005 16:13:03 UTC)
3 DATE_ISO8601 ISO-8601 (example: 2005-08-14T16:13:03+0000)
4 DATE_RFC822 RFC 822 (example: Sun, 14 Aug 2005 16:13:03 UTC)
5 DATE_RFC850 RFC 850 (example: Sunday, 14-Aug-05 16:13:03 UTC)
6 DATE_RFC1036 RFC 1036 (example: Sunday, 14-Aug-05 16:13:03 UTC)
7 DATE_RFC1123 RFC 1123 (example: Sun, 14 Aug 2005 16:13:03 UTC)
8 DATE_RFC2822 RFC 2822 (example: Sun, 14 Aug 2005 16:13:03 +0000)
9 DATE_RSS RSS (example: Sun, 14 Aug 2005 16:13:03 UTC)
10 DATE_W3C World Wide Web Consortium (example: 2005-08-14T16:13:03+0000)

Calendar Functions

The calendar extension provides functions for converting between different calendar formats.

# Function Description
1 cal_days_in_month() Returns the number of days in a month for a specified year and calendar.
2 cal_from_jd() Converts a Julian day count into a date of a specified calendar.
3 cal_info() Returns information about a given calendar.
4 cal_to_jd() Converts a date to a Julian day count.
5 easter_date() Returns the Unix timestamp for midnight on Easter of a specified year.
6 easter_days() Returns the number of days after March 21 on which Easter falls for a specified year.
7 FrenchToJD() Converts a French Republican date to a Julian day count.
8 GregorianToJD() Converts a Gregorian date to a Julian day count.
9 JDDayOfWeek() Returns the day of the week.
10 JDMonthName() Returns a month name.
11 JDToFrench() Converts a Julian day count to a French Republican date.
12 JDToGregorian() Converts a Julian day count to a Gregorian date.
13 jdtojewish() Converts a Julian day count to a Jewish date.
14 JDToJulian() Converts a Julian day count to a Julian date.
15 jdtounix() Converts a Julian day count to a Unix timestamp.
16 JewishToJD() Converts a Jewish date to a Julian day count.
17 JulianToJD() Converts a Julian date to a Julian day count.
18 unixtojd() Converts a Unix timestamp to a Julian day count.

Calendar Constants

# Constant Description
1 CAL_GREGORIAN Gregorian Calendar
2 CAL_JULIAN Julian Calendar
3 CAL_JEWISH Jewish Calendar
4 CAL_FRENCH French Republican Calendar
5 CAL_NUM_CALS The number of available calendars
6 CAL_DOW_DAYNO Day of the week as integer (0 = Sunday, 6 = Saturday)
7 CAL_DOW_SHORT Abbreviated English name of the day of the week
8 CAL_DOW_LONG Full English name of the day of the week
9 CAL_MONTH_GREGORIAN_SHORT Abbreviated Gregorian month name
10 CAL_MONTH_GREGORIAN_LONG Full Gregorian month name
11 CAL_MONTH_JULIAN_SHORT Abbreviated Julian month name
12 CAL_MONTH_JULIAN_LONG Full Julian month name
13 CAL_MONTH_JEWISH Jewish month name
14 CAL_MONTH_FRENCH French Republican month name
15 CAL_EASTER_DEFAULT Calculates Easter using the Julian calendar before 1753, Gregorian after
16 CAL_EASTER_ROMAN Calculates Easter using the Julian calendar before 1583, Gregorian after
17 CAL_EASTER_ALWAYS_GREGORIAN Always calculates Easter using the proleptic Gregorian calendar
18 CAL_EASTER_ALWAYS_JULIAN Always calculates Easter using the Julian calendar
19 CAL_JEWISH_ADD_ALAFIM_GERESH Adds a geresh symbol as thousands separator to the year number
20 CAL_JEWISH_ADD_ALAFIM Adds the word alafim as thousands separator to the year number
21 CAL_JEWISH_ADD_GERESHAYIM Adds a gershayim symbol before the final letter of the day and year numbers

Directory Functions

Directory functions retrieve information about directories and their contents.

# Function Description
1 chdir() Changes the current directory.
2 chroot() Changes the root directory of the current process.
3 dir() Opens a directory handle and returns an object.
4 closedir() Closes a directory handle.
5 getcwd() Returns the current working directory.
6 opendir() Opens a directory handle.
7 readdir() Returns an entry from the directory handle.
8 rewinddir() Resets a directory handle.
9 scandir() Lists files and directories inside a specified path.

Directory Constants

# Constant Description
1 DIRECTORY_SEPARATOR The OS-specific directory separator: \ on Windows, / on Linux and macOS.
2 PATH_SEPARATOR Semicolon on Windows, colon on Linux/macOS.

File System Functions

These functions allow you to access and manipulate the file system, including reading, writing, copying, and inspecting files.

# Function Description
1 basename() Returns the filename component of a path.
2 chgrp() Changes the file group.
3 chmod() Changes the file mode.
4 chown() Changes the file owner.
5 clearstatcache() Clears the file status cache.
6 copy() Copies a file.
7 delete() Deletes a file.
8 dirname() Returns the directory name component of a path.
9 disk_free_space() | diskfreespace() Returns the free space available in a directory.
10 disk_total_space() Returns the total size of a directory.
11 fclose() Closes an open file.
12 feof() Tests for end-of-file on an open file.
13 fflush() Flushes buffered output to an open file.
14 fgetc() Returns a character from an open file.
15 fgetcsv() Parses a line from an open CSV file.
16 fgets() Returns a line from an open file.
17 fgetss() Returns a line with HTML and PHP tags stripped from an open file.
18 file() Reads a file into an array.
19 file_exists() Checks whether a file or directory exists.
20 file_get_contents() Reads a file into a string.
21 file_put_contents() Writes a string to a file.
22 fileatime() Returns the last access time of a file.
23 filectime() Returns the last change time of a file.
24 filegroup() Returns the group ID of a file.
25 fileinode() Returns the inode number of a file.
26 filemtime() Returns the last modification time of a file.
27 fileowner() Returns the user ID (owner) of a file.
28 fileperms() Returns the permissions of a file.
29 filesize() Returns the file size.
30 filetype() Returns the file type.
31 flock() Locks or releases a file.
32 fnmatch() Matches a filename or string against a specified pattern.
33 fopen() Opens a file or URL.
34 fpassthru() Reads from an open file until EOF and writes the result to the output buffer.
35 fputcsv() Formats a line as CSV and writes it to an open file.
36 fputs() Alias of fwrite().
37 fread() Reads from an open file.
38 fscanf() Parses input from an open file according to a specified format.
39 fseek() Seeks to a position in an open file.
40 fstat() Returns information about an open file.
41 ftell() Returns the current position in an open file.
42 ftruncate() Truncates an open file to a specified length.
43 fwrite() Writes to an open file.
44 glob() Returns an array of filenames or directories matching a specified pattern.
45 is_dir() Checks whether a file is a directory.
46 is_executable() Checks whether a file is executable.
47 is_file() Checks whether a file is a regular file.
48 is_link() Checks whether a file is a symbolic link.
49 is_readable() Checks whether a file is readable.
50 is_uploaded_file() Checks whether a file was uploaded via HTTP POST.
51 is_writable() | is_writeable() Checks whether a file is writable.
52 link() Creates a hard link.
53 linkinfo() Returns information about a hard link.
54 lstat() Returns information about a file or symbolic link.
55 mkdir() Creates a directory.
56 move_uploaded_file() Moves an uploaded file to a new location.
57 parse_ini_file() Parses a configuration file.
58 pathinfo() Returns information about a file path.
59 pclose() Closes a pipe opened by popen().
60 popen() Opens a pipe.
61 readfile() Reads a file and writes it to the output buffer.
62 readlink() Returns the target of a symbolic link.
63 realpath() Returns the absolute pathname.
64 rename() Renames a file or directory.
65 rewind() Rewinds a file pointer.
66 rmdir() Removes an empty directory.
67 set_file_buffer() Sets the buffer size of an open file.
68 stat() Returns information about a file.
69 symlink() Creates a symbolic link.
70 tempnam() | tmpfile() Creates a unique temporary file.
71 touch() Sets the access and modification time of a file.
72 umask() Changes file permissions for new files.
73 unlink() Deletes a file.

File System Constants

# Constant Description
1 GLOB_BRACE Expands to match 'a', 'b', or 'c'.
2 GLOB_ONLYDIR Returns only directory entries matching the pattern.
3 GLOB_MARK Adds a slash to each directory returned.
4 GLOB_NOSORT Returns files as they appear in the directory without sorting.
5 GLOB_NOCHECK Returns the search pattern if no matching files are found.
6 GLOB_NOESCAPE Backslashes do not quote metacharacters.
7 GLOB_ERR Stops on read errors such as unreadable directories.
8 PATHINFO_DIRNAME Returns information about the path directory.
9 PATHINFO_BASENAME Returns information about the path basename.
10 PATHINFO_EXTENSION Returns information about the path extension.
11 FILE_USE_INCLUDE_PATH Searches for the file in the include path.
12 FILE_APPEND Appends content to a file. The target file must be writable.
13 FILE_IGNORE_NEW_LINES Omits newline at the end of each array element.
14 FILE_SKIP_EMPTY_LINES Skips empty lines.

Zip Functions

These functions allow you to read and manipulate ZIP archives. The ZIP extension requires libzip.

# Function Description
1 zip_close() Closes a ZIP file.
2 zip_entry_close() Closes an entry in the ZIP file.
3 zip_entry_compressedsize() Returns the compressed size of an entry in the ZIP file.
4 zip_entry_compressionmethod() Returns the compression method of an entry in the ZIP file.
5 zip_entry_filesize() Returns the actual file size of an entry in the ZIP file.
6 zip_entry_name() Returns the name of an entry in the ZIP file.
7 zip_entry_open() Opens an entry in the ZIP file for reading.
8 zip_entry_read() Reads from an open entry in the ZIP file.
9 zip_open() Opens a ZIP file.
10 zip_read() Reads the next entry in the ZIP file.

Filter Functions

Filter functions validate and sanitize data coming from external sources such as forms, APIs, and URLs. They are the recommended approach for handling user input safely in PHP.

# Function Description
1 filter_has_var() Checks if a variable of a specified input type exists.
2 filter_id() Returns the ID number of a specified filter.
3 filter_input() Gets input from outside the script and filters it.
4 filter_input_array() Gets multiple inputs from outside the script and filters them.
5 filter_list() Returns an array of all supported filters.
6 filter_var_array() Gets and filters multiple variables.
7 filter_var() Gets and filters a single variable.

Filter Constants

# Constant Description
1 FILTER_DEFAULT Does nothing; optionally strips or encodes special characters. Equivalent to FILTER_UNSAFE_RAW.
2 FILTER_FLAG_NONE Allows no flags.
3 FILTER_FLAG_ALLOW_OCTAL Allows octal number inputs starting with zero (0-7 digits only).
4 FILTER_FLAG_ALLOW_HEX Allows hexadecimal inputs starting with 0x/0X (a-fA-F0-9 only).
5 FILTER_FLAG_STRIP_LOW Strips characters with ASCII value lower than 32.
6 FILTER_FLAG_STRIP_HIGH Strips characters with ASCII value greater than 127.
7 FILTER_FLAG_ENCODE_LOW Encodes characters with ASCII value lower than 32.
8 FILTER_FLAG_ENCODE_HIGH Encodes characters with ASCII value greater than 127.
9 FILTER_FLAG_ENCODE_AMP Encodes &.
10 FILTER_FLAG_NO_ENCODE_QUOTES Does not encode single or double quotes.
11 FILTER_FLAG_EMPTY_STRING_NULL Not currently in use.
12 FILTER_FLAG_ALLOW_FRACTION Allows a period (.) as a fractional separator in numbers.
13 FILTER_FLAG_ALLOW_THOUSAND Allows a comma (,) as a thousands separator in numbers.
14 FILTER_FLAG_ALLOW_SCIENTIFIC Allows e or E for scientific notation in numbers.
15 FILTER_FLAG_PATH_REQUIRED The URL must contain a path part.
16 FILTER_FLAG_QUERY_REQUIRED The URL must contain a query string.
17 FILTER_FLAG_IPV4 Allows the IP address to be in IPv4 format.
18 FILTER_FLAG_IPV6 Allows the IP address to be in IPv6 format.
19 FILTER_FLAG_NO_RES_RANGE Fails validation for reserved IPv4 and IPv6 ranges.
20 FILTER_FLAG_NO_PRIV_RANGE Fails validation for private IPv4 ranges and IPv6 addresses starting with FD or FC.
21 FILTER_FLAG_EMAIL_UNICODE Allows the local part of an email address to contain Unicode characters.
22 FILTER_REQUIRE_SCALAR The value must be a scalar.
23 FILTER_REQUIRE_ARRAY The value must be an array.
24 FILTER_FORCE_ARRAY Treats a scalar value as an array with the scalar value as its only element.
25 FILTER_NULL_ON_FAILURE Returns NULL on failure for unrecognized boolean values.
26 FILTER_VALIDATE_BOOLEAN Validates a boolean.
27 FILTER_VALIDATE_EMAIL Validates a value as a valid email address.
28 FILTER_VALIDATE_FLOAT Validates a value as a float.
29 FILTER_VALIDATE_INT Validates a value as an integer.
30 FILTER_VALIDATE_IP Validates a value as an IP address.
31 FILTER_VALIDATE_MAC Validates a value as a MAC address.
32 FILTER_VALIDATE_REGEXP Validates a value against a regular expression.
33 FILTER_VALIDATE_URL Validates a value as a URL.
34 FILTER_SANITIZE_EMAIL Removes all illegal characters from an email address.
35 FILTER_SANITIZE_ENCODED Removes or encodes special characters.
36 FILTER_SANITIZE_MAGIC_QUOTES Applies addslashes().
37 FILTER_SANITIZE_NUMBER_FLOAT Removes all characters except digits, +/- signs, and optionally .,eE.
38 FILTER_SANITIZE_NUMBER_INT Removes all characters except digits and +/- signs.
39 FILTER_SANITIZE_SPECIAL_CHARS Removes special characters.
40 FILTER_SANITIZE_STRING Removes tags and special characters from a string.
41 FILTER_SANITIZE_STRIPPED Alias of FILTER_SANITIZE_STRING.
42 FILTER_SANITIZE_URL Removes all illegal characters from a URL.
43 FILTER_UNSAFE_RAW Does nothing; optionally strips or encodes special characters.
44 FILTER_CALLBACK Calls a user-defined function to filter data.
45 INPUT_POST POST variables.
46 INPUT_GET GET variables.
47 INPUT_COOKIE COOKIE variables.
48 INPUT_ENV ENV variables.
49 INPUT_SERVER SERVER variables.

Mail Functions

The mail function allows sending email directly from a PHP script.

# Function Description
1 ezmlm_hash() Calculates the hash value used by the EZMLM mailing list system.
2 mail() Sends an email directly from a script.

FTP Functions

FTP functions give your script access to file servers through the File Transfer Protocol. Use them to open connections, upload and download files, rename, delete, and retrieve file information remotely.

# Function Description
1 ftp_alloc() Allocates space for a file to be uploaded to the FTP server.
2 ftp_cdup() Changes the current directory to the parent directory on the FTP server.
3 ftp_chdir() Changes the current directory on the FTP server.
4 ftp_chmod() Sets permissions on a file via FTP.
5 ftp_close() Closes an FTP connection.
6 ftp_connect() Opens an FTP connection.
7 ftp_delete() Deletes a file on the FTP server.
8 ftp_exec() Executes a program or command on the FTP server.
9 ftp_fget() Downloads a file from the FTP server and saves it to an open file.
10 ftp_fput() Uploads from an open file and saves it to the FTP server.
11 ftp_get_option() Returns runtime options for the FTP connection.
12 ftp_get() Downloads a file from the FTP server.
13 ftp_login() Logs in to an FTP connection.
14 ftp_mdtm() Returns the last modified time of a specified file.
15 ftp_mkdir() Creates a new directory on the FTP server.
16 ftp_nb_continue() Continues retrieving or sending a file (non-blocking).
17 ftp_nb_fget() Downloads a file from the FTP server to an open file (non-blocking).
18 ftp_nb_fput() Uploads from an open file and saves to the FTP server (non-blocking).
19 ftp_nb_get() Downloads a file from the FTP server (non-blocking).
20 ftp_nb_put() Uploads a file to the FTP server (non-blocking).
21 ftp_nlist() Lists files in a specified directory on the FTP server.
22 ftp_pasv() Turns passive mode on or off.
23 ftp_put() Uploads a file to the FTP server.
24 ftp_pwd() Returns the current directory name.
25 ftp_quit() Alias of ftp_close().
26 ftp_raw() Sends a raw command to the FTP server.
27 ftp_rawlist() Returns a detailed list of files in the specified directory.
28 ftp_rename() Renames a file or directory on the FTP server.
29 ftp_rmdir() Removes a directory on the FTP server.
30 ftp_set_option() Sets runtime options for the FTP connection.
31 ftp_site() Sends a SITE command to the server.
32 ftp_size() Returns the size of a specified file.
33 ftp_ssl_connect() Opens a secure SSL-FTP connection.
34 ftp_systype() Returns the system type identifier of the FTP server.

FTP Constants

# Constant Description
1 FTP_ASCII | FTP_TEXT FTP transfer mode for text files.
2 FTP_BINARY | FTP_IMAGE FTP transfer mode for binary files.
3 FTP_TIMEOUT_SEC Timeout used for network operations.
4 FTP_AUTOSEEK Sets miscellaneous runtime FTP options.
5 FTP_AUTORESUME Automatically determines resume and start positions for GET and PUT requests. Requires FTP_AUTOSEEK.
6 FTP_FAILED Asynchronous transfer has failed.
7 FTP_FINISHED Asynchronous transfer has completed.
8 FTP_MOREDATA Asynchronous transfer is in progress.

HTTP Functions

# Function Description
1 header() Sends a raw HTTP header to a client.
2 headers_list() Returns a list of response headers sent or ready to send.
3 headers_sent() Checks if or where HTTP headers have been sent.
4 setcookie() Sends an HTTP cookie to a client.
5 setrawcookie() Sends an HTTP cookie without URL-encoding the cookie value.

SimpleXML Functions

SimpleXML converts an XML document into a data structure that can be iterated like arrays and objects. It is the fastest way to read and manipulate XML data in PHP when the document structure is known.

# Function Description
1 __construct() Creates a new SimpleXMLElement object.
2 addAttribute() Adds an attribute to a SimpleXML element.
3 addChild() Adds a child element to a SimpleXML element.
4 asXML() Returns an XML string from a SimpleXML element.
5 attributes() Gets a SimpleXML element's attributes.
6 children() Gets the children of a specified node.
7 getDocNamespaces() Gets the namespaces of an XML document.
8 getName() Gets the name of a SimpleXML element.
9 getNamespace() Gets namespaces from XML data.
10 registerXPathNamespace() Creates a namespace context for the next XPath query.
11 simplexml_import_dom() Gets a SimpleXMLElement object from a DOM node.
12 simplexml_load_file() Gets a SimpleXMLElement object from an XML document.
13 simplexml_load_string() Gets a SimpleXMLElement object from an XML string.
14 xpath() Runs an XPath query on XML data.

LIBXML Functions

LIBXML functions are used with SimpleXML, XSLT, and DOM functions.

# Function Description
1 libxml_clear_errors() Clears the libxml error buffer.
2 libxml_get_errors() Retrieves an array of errors.
3 libxml_get_last_error() Retrieves the last error from libxml.
4 libxml_set_streams_context() Sets the streams context for the next libxml document load or write.
5 libxml_use_internal_errors() Disables libxml errors and allows user to fetch error information as needed.

LIBXML Constants

# Constant Description
1 LIBXML_BIGLINES Reports line numbers greater than 65535 correctly.
2 LIBXML_COMPACT Sets small node allocation optimization to improve performance.
3 LIBXML_DOTTED_VERSION Returns the dotted libxml version (e.g. 2.6.5).
4 LIBXML_DTDATTR Sets default DTD attributes.
5 LIBXML_DTDLOAD Loads the external subset.
6 LIBXML_DTDVALID Validates with the DTD.
7 LIBXML_ERR_ERROR Gets recoverable errors.
8 LIBXML_ERR_FATAL Gets fatal errors.
9 LIBXML_ERR_NONE Gets no errors.
10 LIBXML_ERR_WARNING Gets simple warnings.
11 LIBXML_HTML_NOIMPLIED Turns off automatic adding of implied html/body elements.
12 LIBXML_HTML_NODEFDTD Prevents a default doctype from being added when none is found.
13 LIBXML_NOBLANKS Removes blank nodes.
14 LIBXML_NOCDATA Sets CDATA sections as text nodes.
15 LIBXML_NOEMPTYTAG Changes empty tags (e.g. <br/> to <br></br>) in DOMDocument save functions.
16 LIBXML_NOENT Substitutes entities.
17 LIBXML_NOERROR Suppresses error reports.
18 LIBXML_NONET Stops network access while loading documents.
19 LIBXML_NOWARNING Suppresses warning reports.
20 LIBXML_NOXMLDECL Drops the XML declaration when saving a document.
21 LIBXML_NSCLEAN Removes redundant namespace declarations.
22 LIBXML_PARSEHUGE Relaxes hardcoded parser limits including maximum document depth and text node size.
23 LIBXML_PEDANTIC Enables pedantic error reporting.
24 LIBXML_XINCLUDE Uses XInclude substitution.
25 LIBXML_VERSION Returns the libxml version as an integer (e.g. 20605).
26 LIBXML_SCHEMA_CREATE Creates default or fixed value nodes during XSD schema validation.

XML Parser Functions

XML parser functions create event-driven parsers for reading XML documents. They do not validate documents but enable handlers to be defined for XML events like element start/end and character data.

# Function Description
1 utf8_decode() Decodes a UTF-8 string to ISO-8859-1.
2 utf8_encode() Encodes an ISO-8859-1 string to UTF-8.
3 xml_error_string() Gets an error string from the XML parser.
4 xml_get_current_byte_index() Gets the current byte index from the XML parser.
5 xml_get_current_column_number() Gets the current column number from the XML parser.
6 xml_get_current_line_number() Gets the current line number from the XML parser.
7 xml_get_error_code() Gets an error code from the XML parser.
8 xml_parse() Parses an XML document.
9 xml_parse_into_struct() Parses XML data into an array.
10 xml_parser_create_ns() Creates an XML parser with namespace support.
11 xml_parser_create() Creates an XML parser.
12 xml_parser_free() Frees an XML parser.
13 xml_parser_get_option() Gets options from an XML parser.
14 xml_parser_set_option() Sets options on an XML parser.
15 xml_set_character_data_handler() Sets a handler function for character data.
16 xml_set_default_handler() Sets the default handler function.
17 xml_set_element_handler() Sets handler functions for the start and end of elements.
18 xml_set_end_namespace_decl_handler() Sets a handler function for the end of namespace declarations.
19 xml_set_external_entity_ref_handler() Sets handler functions for external entities.
20 xml_set_notation_decl_handler() Sets a handler function for notation declarations.
21 xml_set_object() Uses the XML parser within an object.
22 xml_set_processing_instruction_handler() Sets a handler function for processing instructions.
23 xml_set_start_namespace_decl_handler() Sets a handler function for the start of namespace declarations.
24 xml_set_unparsed_entity_decl_handler() Sets a handler function for unparsed entity declarations.

XML Parser Constants

Constant Constant
XML_ERROR_NONE XML_ERROR_ASYNC_ENTITY
XML_ERROR_NO_MEMORY XML_ERROR_BAD_CHAR_REF
XML_ERROR_SYNTAX XML_ERROR_BINARY_ENTITY_REF
XML_ERROR_NO_ELEMENTS XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
XML_ERROR_INVALID_TOKEN XML_ERROR_MISPLACED_XML_PI
XML_ERROR_UNCLOSED_TOKEN XML_ERROR_UNKNOWN_ENCODING
XML_ERROR_PARTIAL_CHAR XML_ERROR_INCORRECT_ENCODING
XML_ERROR_TAG_MISMATCH XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_DUPLICATE_ATTRIBUTE XML_ERROR_EXTERNAL_ENTITY_HANDLING
XML_ERROR_JUNK_AFTER_DOC_ELEMENT XML_OPTION_CASE_FOLDING
XML_ERROR_PARAM_ENTITY_REF XML_OPTION_TARGET_ENCODING
XML_ERROR_UNDEFINED_ENTITY XML_OPTION_SKIP_TAGSTART
XML_ERROR_RECURSIVE_ENTITY_REF XML_OPTION_SKIP_WHITE

MySQLi Functions

MySQLi (MySQL Improved) functions let your PHP scripts interact with MySQL database servers. Use prepared statements to protect against SQL injection when handling user input in your queries.

# Function / Property Description
1 mysqli::$affected_rows Gets the number of affected rows in the previous MySQL operation.
2 mysqli::autocommit() Turns auto-committing of database modifications on or off.
3 mysqli::change_user() Changes the user of the specified database connection.
4 mysqli::character_set_name() Returns the default character set for the database connection.
5 mysqli::$client_info Gets MySQL client info.
6 mysqli::$client_version Returns the MySQL client version as a string.
7 mysqli::close() Closes a previously opened database connection.
8 mysqli::commit() Commits the current transaction.
9 mysqli::$connect_errno Returns the error code from the last connection attempt.
10 mysqli::$connect_error Returns a string description of the last connection error.
11 mysqli::__construct() Opens a new connection to the MySQL server.
12 mysqli::debug() Performs debugging operations.
13 mysqli::dump_debug_info() Dumps debugging information into the log.
14 mysqli::$errno Returns the error code for the most recent function call.
15 mysqli::$error_list Returns a list of errors from the last command executed.
16 mysqli::$error Returns a string description of the last error.
17 mysqli::$field_count Returns the number of columns for the most recent query.
18 mysqli::get_charset() Returns a character set object.
19 mysqli::get_client_info() Gets MySQL client info.
20 mysqli_get_client_stats() Returns client per-process statistics.
21 mysqli_get_client_version() Returns the MySQL client version as a string.
22 mysqli::get_connection_stats() Returns statistics about the client connection.
23 mysqli::$host_info Returns a string representing the type of connection used.
24 mysqli::$protocol_version Returns the version of the MySQL protocol used.
25 mysqli::$server_info Returns the version of the MySQL server.
26 mysqli::$server_version Returns the MySQL server version as an integer.
27 mysqli::get_warnings() Gets the result of SHOW WARNINGS.
28 mysqli::$info Retrieves information about the most recently executed query.
29 mysqli::init() Initializes MySQLi and returns a resource for use with mysqli_real_connect().
30 mysqli::$insert_id Returns the auto-generated ID used in the last query.
31 mysqli::kill() Asks the server to kill a MySQL thread.
32 mysqli::more_results() Checks if there are more query results from a multi-query.
33 mysqli::multi_query() Performs a query on a database.
34 mysqli::next_result() Prepares the next result from a multi-query.
35 mysqli::options() Sets options.
36 mysqli::ping() Pings a server connection or tries to reconnect if the connection has gone down.
37 mysqli::poll() Polls connections.
38 mysqli::prepare() Prepares a SQL statement for execution.
39 mysqli::query() Performs a query on the database.
40 mysqli::real_connect() Opens a connection to a MySQL server.
41 mysqli::real_escape_string() Escapes special characters in a string for use in a SQL statement, using the current connection charset.
42 mysqli::real_query() Executes a SQL query.
43 mysqli::reap_async_query() Gets the result from an async query.
44 mysqli::refresh() Refreshes tables, logs, or status as specified.
45 mysqli::rollback() Rolls back the current transaction.
46 mysqli::select_db() Selects the default database for database queries.
47 mysqli::send_query() Sends the query and returns.
48 mysqli::set_charset() Sets the default client character set.
49 mysqli::set_local_infile_default() Unsets a user-defined handler for the LOAD LOCAL INFILE command.
50 mysqli::set_local_infile_handler() Sets a callback function for the LOAD DATA LOCAL INFILE command.
51 mysqli::$sqlstate Returns the SQLSTATE error from the previous MySQL operation.
52 mysqli::ssl_set() Used for establishing secure connections using SSL.
53 mysqli::stat() Gets the current system status.
54 mysqli::stmt_init() Initializes a statement and returns an object for use with mysqli_stmt_prepare().
55 mysqli::store_result() Transfers a result set from the last query.
56 mysqli::$thread_id Returns the thread ID for the current connection.
57 mysqli::thread_safe() Returns whether thread safety is enabled.
58 mysqli::use_result() Initiates a result set retrieval.
59 mysqli::$warning_count Returns the number of warnings from the last query.

MySQLi Statements

# Function / Property Description
1 mysqli_stmt::$affected_rows Returns the total number of rows changed, deleted, or inserted by the last executed statement.
2 mysqli_stmt::attr_get() Gets the current value of a statement attribute.
3 mysqli_stmt::attr_set() Modifies the behavior of a prepared statement.
4 mysqli_stmt::bind_param() Binds variables to a prepared statement as parameters.
5 mysqli_stmt::bind_result() Binds variables to a prepared statement for result storage.
6 mysqli_stmt::close() Closes a prepared statement.
7 mysqli_stmt::data_seek() Seeks to an arbitrary row in the statement result set.
8 mysqli_stmt::$errno Returns the error code for the most recent statement call.
9 mysqli_stmt::$error_list Returns a list of errors from the last statement executed.
10 mysqli_stmt::$error Returns a string description of the last statement error.
11 mysqli_stmt::execute() Executes a prepared query.
12 mysqli_stmt::fetch() Fetches results from a prepared statement into bound variables.
13 mysqli_stmt::$field_count Returns the number of fields in the given statement.
14 mysqli_stmt::free_result() Frees stored result memory for the given statement handle.
15 mysqli_stmt::get_result() Gets a result set from a prepared statement.
16 mysqli_stmt::get_warnings() Gets the result of SHOW WARNINGS.
17 mysqli_stmt::$insert_id Gets the ID generated from the previous INSERT operation.
18 mysqli_stmt::more_results() Checks if there are more query results from a multiple query.
19 mysqli_stmt::next_result() Reads the next result from a multiple query.
20 mysqli_stmt::$num_rows Returns the number of rows in the statement result set.
21 mysqli_stmt::$param_count Returns the number of parameters for the given statement.
22 mysqli_stmt::prepare() Prepares a SQL statement for execution.
23 mysqli_stmt::reset() Resets a prepared statement.
24 mysqli_stmt::result_metadata() Returns result set metadata from a prepared statement.
25 mysqli_stmt::send_long_data() Sends data in blocks.
26 mysqli_stmt::$sqlstate Returns the SQLSTATE error from the previous statement operation.
27 mysqli_stmt::store_result() Transfers a result set from a prepared statement.

MySQLi Result Class

# Function / Property Description
1 mysqli_result::$current_field Gets the current field offset of a result pointer.
2 mysqli_result::data_seek() Adjusts the result pointer to an arbitrary row in the result.
3 mysqli_result::fetch_all() Fetches all result rows as an associative array, a numeric array, or both.
4 mysqli_result::fetch_array() Fetches a result row as an associative array, a numeric array, or both.
5 mysqli_result::fetch_assoc() Fetches a result row as an associative array.
6 mysqli_result::fetch_field_direct() Fetches meta-data for a single field.
7 mysqli_result::fetch_field() Returns the next field in the result set.
8 mysqli_result::fetch_fields() Returns an array of objects representing the fields in a result set.
9 mysqli_result::fetch_object() Returns the current row of a result set as an object.
10 mysqli_result::fetch_row() Gets a result row as an enumerated array.
11 mysqli_result::$field_count Gets the number of fields in a result.
12 mysqli_result::field_seek() Sets the result pointer to a specified field offset.
13 mysqli_result::free() Frees the memory associated with a result.
14 mysqli_result::$lengths Returns the lengths of the columns of the current row in the result set.
15 mysqli_result::$num_rows Gets the number of rows in a result.

MySQLi Driver Class

# Function / Property Description
1 mysqli_driver::embedded_server_end() Stops the embedded server.
2 mysqli_driver::embedded_server_start() Initializes and starts the embedded server.
3 mysqli_driver::$report_mode Enables or disables internal report functions.
4 mysqli_driver::$client_info The client API header version.
5 mysqli_driver::$client_version The client version.
6 mysqli_driver::$driver_version The MySQLi driver version.
7 mysqli_driver::$embedded Whether MySQLi embedded support is enabled.
8 mysqli_driver::$reconnect Allows or prevents reconnection.

MySQLi Warning Class

# Property / Method Description
1 mysqli_warning::__construct() Constructor for the warning object.
2 mysqli_warning::next() Advances to the next warning.
3 mysqli_warning::$message Warning message string.
4 mysqli_warning::$sqlstate SQL state.
5 mysqli_warning::$errno Error number.

MySQLi Constants

# Constant Description
1 MYSQLI_READ_DEFAULT_GROUP Reads options from the named group in my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE.
2 MYSQLI_READ_DEFAULT_FILE Reads options from a named option file instead of my.cnf.
3 MYSQLI_OPT_CONNECT_TIMEOUT Connection timeout in seconds.
4 MYSQLI_OPT_LOCAL_INFILE Enables the LOAD LOCAL INFILE command.
5 MYSQLI_INIT_COMMAND Command to execute when connecting to MySQL. Re-executed automatically on reconnect.
6 MYSQLI_CLIENT_SSL Uses SSL (encrypted protocol).
7 MYSQLI_CLIENT_COMPRESS Uses compression protocol.
8 MYSQLI_CLIENT_INTERACTIVE Allows interactive_timeout seconds of inactivity instead of wait_timeout before closing.
9 MYSQLI_CLIENT_IGNORE_SPACE Allows spaces after function names, making all function names reserved words.
10 MYSQLI_CLIENT_NO_SCHEMA Disallows the db_name.tbl_name.col_name syntax.
11 MYSQLI_CLIENT_MULTI_QUERIES Allows multiple semicolon-delimited queries in a single mysqli_query() call.
12 MYSQLI_STORE_RESULT For using buffered result sets.
13 MYSQLI_USE_RESULT For using unbuffered result sets.
14 MYSQLI_ASSOC Columns returned with fieldname as the array index.
15 MYSQLI_NUM Columns returned with an enumerated index.
16 MYSQLI_BOTH Columns returned with both numerical and associative indexes.
17 MYSQLI_NOT_NULL_FLAG Field is defined as NOT NULL.
18 MYSQLI_PRI_KEY_FLAG Field is part of a primary index.
19 MYSQLI_UNIQUE_KEY_FLAG Field is part of a unique index.
20 MYSQLI_MULTIPLE_KEY_FLAG Field is part of an index.
21 MYSQLI_BLOB_FLAG Field is defined as BLOB.
22 MYSQLI_UNSIGNED_FLAG Field is defined as UNSIGNED.
23 MYSQLI_ZEROFILL_FLAG Field is defined as ZEROFILL.
24 MYSQLI_AUTO_INCREMENT_FLAG Field is defined as AUTO_INCREMENT.
25 MYSQLI_TIMESTAMP_FLAG Field is defined as TIMESTAMP.
26 MYSQLI_SET_FLAG Field is defined as SET.
27 MYSQLI_NUM_FLAG Field is defined as NUMERIC.
28 MYSQLI_PART_KEY_FLAG Field is part of a multi-index.
29 MYSQLI_GROUP_FLAG Field is part of GROUP BY.
30 MYSQLI_TYPE_DECIMAL Field is defined as DECIMAL.
31 MYSQLI_TYPE_NEWDECIMAL Precision math DECIMAL or NUMERIC field (MySQL 5.0.3+).
32 MYSQLI_TYPE_BIT Field is defined as BIT (MySQL 5.0.3+).
33 MYSQLI_TYPE_TINY Field is defined as TINYINT.
34 MYSQLI_TYPE_SHORT Field is defined as SMALLINT.
35 MYSQLI_TYPE_LONG Field is defined as INT.
36 MYSQLI_TYPE_FLOAT Field is defined as FLOAT.
37 MYSQLI_TYPE_DOUBLE Field is defined as DOUBLE.
38 MYSQLI_TYPE_NULL Field is NULL.
39 MYSQLI_TYPE_TIMESTAMP Field is defined as TIMESTAMP.
40 MYSQLI_TYPE_LONGLONG Field is defined as BIGINT.
41 MYSQLI_TYPE_INT24 Field is defined as MEDIUMINT.
42 MYSQLI_TYPE_DATE Field is defined as DATE.
43 MYSQLI_TYPE_TIME Field is defined as TIME.
44 MYSQLI_TYPE_DATETIME Field is defined as DATETIME.
45 MYSQLI_TYPE_YEAR Field is defined as YEAR.
46 MYSQLI_TYPE_NEWDATE Field is defined as DATE.
47 MYSQLI_TYPE_INTERVAL Field is defined as INTERVAL.
48 MYSQLI_TYPE_ENUM Field is defined as ENUM.
49 MYSQLI_TYPE_SET Field is defined as SET.
50 MYSQLI_TYPE_TINY_BLOB Field is defined as TINYBLOB.
51 MYSQLI_TYPE_MEDIUM_BLOB Field is defined as MEDIUMBLOB.
52 MYSQLI_TYPE_LONG_BLOB Field is defined as LONGBLOB.
53 MYSQLI_TYPE_BLOB Field is defined as BLOB.
54 MYSQLI_TYPE_VAR_STRING Field is defined as VARCHAR.
55 MYSQLI_TYPE_STRING Field is defined as CHAR or BINARY.
56 MYSQLI_TYPE_CHAR Field is defined as TINYINT. For CHAR, see MYSQLI_TYPE_STRING.
57 MYSQLI_TYPE_GEOMETRY Field is defined as GEOMETRY.
58 MYSQLI_NEED_DATA More data available for bind variable.
59 MYSQLI_NO_DATA No more data available for bind variable.
60 MYSQLI_DATA_TRUNCATED Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.
61 MYSQLI_ENUM_FLAG Field is defined as ENUM. Available since PHP 5.3.0.
62 MYSQLI_REPORT_INDEX Reports if no index or a bad index was used in a query.
63 MYSQLI_REPORT_ERROR Reports errors from MySQLi function calls.
64 MYSQLI_REPORT_STRICT Throws a mysqli_sql_exception for errors instead of warnings.
65 MYSQLI_REPORT_ALL Sets all reporting options on.
66 MYSQLI_REPORT_OFF Turns reporting off.
67 MYSQLI_DEBUG_TRACE_ENABLED Set to 1 if mysqli_debug() functionality is enabled.
68 MYSQLI_REFRESH_GRANT Refreshes the grant tables.
69 MYSQLI_REFRESH_LOG Flushes the logs (equivalent to FLUSH LOGS).
70 MYSQLI_REFRESH_TABLES Flushes the table cache (equivalent to FLUSH TABLES).
71 MYSQLI_REFRESH_HOSTS Flushes the host cache (equivalent to FLUSH HOSTS).
72 MYSQLI_REFRESH_STATUS Resets the status variables (equivalent to FLUSH STATUS).
73 MYSQLI_REFRESH_THREADS Flushes the thread cache.
74 MYSQLI_REFRESH_SLAVE On a replica server: resets master info and restarts replication (equivalent to RESET SLAVE).
75 MYSQLI_REFRESH_MASTER On a primary server: removes binary log files listed in the index (equivalent to RESET MASTER).

Misc Functions

These miscellaneous functions cover connection management, constants, code execution, and utility tasks. Their behavior is affected by settings in php.ini.

# Function Description
1 connection_aborted() Checks whether the client has disconnected.
2 connection_status() Returns the current connection status.
3 connection_timeout() Deprecated since PHP 4.0.5.
4 constant() Returns the value of a constant.
5 define() Defines a constant.
6 defined() Checks whether a constant exists.
7 die() Prints a message and exits the current script.
8 eval() Evaluates a string as PHP code.
9 exit() Prints a message and exits the current script.
10 get_browser() Returns the capabilities of the user's browser.
11 highlight_file() Outputs a file with PHP syntax highlighting.
12 highlight_string() Outputs a string with PHP syntax highlighting.
13 ignore_user_abort() Sets whether a remote client can abort a running script.
14 pack() Packs data into a binary string.
15 php_strip_whitespace() Removes whitespace and PHP comments from the source code of a file.
16 show_source() Alias of highlight_file().
17 sleep() Delays code execution for a number of seconds.
18 time_nanosleep() Delays code execution for a number of seconds and nanoseconds.
19 time_sleep_until() Delays code execution until a specified time.
20 uniqid() Generates a unique ID.
21 unpack() Unpacks data from a binary string.
22 usleep() Delays code execution for a number of microseconds.

Misc Constants

# Constant Description
1 CONNECTION_ABORTED Connection aborted by the user or a network error.
2 CONNECTION_NORMAL Connection is running normally.
3 CONNECTION_TIMEOUT Connection timed out.
4 __COMPILER_HALT_OFFSET__ Determines the byte position of the data start.

Object-Oriented Programming Magic Methods

PHP supports full object-oriented programming including classes, inheritance, interfaces, and traits. Magic methods are special hooks that PHP calls automatically in response to certain events on an object. Every magic method starts with a double underscore.

The example below shows inheritance, a public function, and the most common magic methods in action:


class Vehicle {
    public string $make;

    public function __construct(string $make) {
        $this->make = $make;
    }

    public function describe(): string {
        return "Vehicle: {$this->make}";
    }
}

class Car extends Vehicle {
    public function describe(): string {
        return "Car: {$this->make}";
    }

    public function __toString(): string {
        return $this->describe();
    }
}

$car = new Car("Toyota");
echo $car; // Car: Toyota
# Method Description
1 __construct() Called on each newly created object. Used for initialization before the object is used.
2 __destruct() Called when there are no more references to the object, or during shutdown.
3 __callStatic() Triggered when invoking inaccessible methods in a static context.
4 __call() Triggered when invoking inaccessible methods in an object context.
5 __get() Used for reading data from inaccessible properties.
6 __set() Triggered when writing data to inaccessible properties.
7 __isset() Triggered by calling isset() or empty() on inaccessible properties.
8 __unset() Invoked when unset() is used on inaccessible properties.
9 __sleep() Used to commit pending data or perform cleanup before serialization. Also useful for omitting large unnecessary properties.
10 __wakeup() Used to re-establish database connections or perform reinitialization tasks after deserialization.
11 __toString() Defines how the class behaves when treated as a string.
12 __invoke() Called when a script attempts to call an object as a function.
13 __set_state() Called for classes exported by var_export() since PHP 5.1.0.
14 __clone() Called after cloning completes. Allows the newly cloned object to modify any properties that need to differ from the original.

Error Functions

Error functions let you control how PHP handles, reports, and logs errors. Combined with exception handlers, they give you full control over error behavior in production and development environments.

# Function Description
1 debug_backtrace() Generates a backtrace.
2 debug_print_backtrace() Prints a backtrace.
3 error_get_last() Gets the last error that occurred.
4 error_log() Sends an error to a server error log, a file, or a remote destination.
5 error_reporting() Specifies which errors are reported.
6 restore_error_handler() Restores the previous error handler.
7 restore_exception_handler() Restores the previous exception handler.
8 set_error_handler() Sets a user-defined function to handle errors.
9 set_exception_handler() Sets a user-defined function to handle exceptions.
10 trigger_error() Creates a user-defined error message.
11 user_error() Alias of trigger_error().

Error Constants

# Constant Description
1 E_ERROR (1) Fatal run-time errors that cannot be recovered from. Script execution halts.
2 E_WARNING (2) Non-fatal run-time errors. Script execution continues.
3 E_PARSE (4) Compile-time parse errors generated by the parser.
4 E_NOTICE (8) Run-time notices indicating something that might be an error or could happen normally.
5 E_CORE_ERROR (16) Fatal errors during PHP startup, similar to E_ERROR in the PHP core.
6 E_CORE_WARNING (32) Non-fatal errors during PHP startup, similar to E_WARNING in the PHP core.
7 E_COMPILE_ERROR (64) Fatal compile-time errors generated by the Zend Scripting Engine.
8 E_COMPILE_WARNING (128) Non-fatal compile-time warnings generated by the Zend Scripting Engine.
9 E_USER_ERROR (256) Fatal user-generated error using trigger_error().
10 E_USER_WARNING (512) Non-fatal user-generated warning using trigger_error().
11 E_USER_NOTICE (1024) User-generated notice using trigger_error().
12 E_STRICT (2048) Run-time notices where PHP suggests code changes for better interoperability.
13 E_RECOVERABLE_ERROR (4096) Catchable fatal error that can be handled by a user-defined handler.
14 E_ALL (6143) All errors and warnings except E_STRICT.

Frequently Asked Questions

What is a PHP cheat sheet and how do I use it?

A PHP cheat sheet is a quick reference guide listing the language's built-in functions, constants, syntax, and constructs organized by category. Use it while coding to quickly look up a function's purpose without leaving your editor. Bookmark this page and use the table of contents to jump directly to the section you need.

What are the most commonly used PHP functions?

The most frequently used PHP built-in functions are echo(), strlen(), str_replace(), array_map(), array_filter(), array_push(), count(), isset(), in_array(), date(), json_encode(), json_decode(), file_get_contents(), and mysqli::query(). For web development, htmlspecialchars() and filter_input() are critical for sanitizing user input.

Which PHP functions are deprecated or removed in PHP 8?

Several functions were removed in PHP 8.0: each() (use foreach instead), money_format() (use NumberFormatter), and import_request_variables() (removed in PHP 5.4). The create_function() function was also removed. Always check the PHP 8 migration guide before upgrading a legacy codebase.

What is the difference between echo and print in PHP?

echo and print both output strings, but echo can take multiple comma-separated arguments and has no return value, making it marginally faster. print always returns 1, which means it can be used in expressions. In practice, echo is the standard choice for most developers.

How do I use array_map vs array_filter in PHP?

Use array_map() when you want to transform every element in an array and get a new array of the same length back. Use array_filter() when you want to remove elements that do not meet a condition. For example: array_map(fn($n) => $n * 2, $arr) doubles every value; array_filter($arr, fn($n) => $n > 5) returns only values greater than 5.

What are PHP magic methods in OOP?

Magic methods are special built-in methods that PHP calls automatically in response to events on an object. They always begin with a double underscore (e.g., __construct(), __toString(), __get()). You define them in your class to customize object behavior for initialization, serialization, property access, and more. The full list is in the OOP section above.

How do I connect to a MySQL database in PHP using MySQLi?

Use the MySQLi constructor to open a connection, then use prepared statements for any queries that include user input. Example: $mysqli = new mysqli("localhost", "user", "password", "database"); followed by $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?"). Always close the connection with $mysqli->close() when done.

What PHP string functions should I know for sanitizing user input?

For sanitizing user input, the most important tools are filter_input() with the appropriate filter constant (e.g., FILTER_SANITIZE_EMAIL), htmlspecialchars() to prevent XSS, strip_tags() to remove HTML, and trim() to clean whitespace. For database input specifically, use MySQLi prepared statements with bind_param() rather than string escaping alone.

What to Learn Next

This PHP cheat sheet covers the full range of built-in functions and constants, but knowing the language is only part of building production applications. From here, explore PHP frameworks like Laravel and Symfony to understand how structure and conventions accelerate web development. If you are preparing for interviews, the PHP interview questions guide covers the concepts and patterns employers test most.

For those still building foundational skills, this list of the best PHP books includes options suited to every level. And if you want structured learning with video instruction, check out the best PHP certifications to find a path that fits your goals.

For complete documentation on any function and even more detail on PHP, visit php.net/manual.

By Barnali Chanda

Barnali is a software developer, who eventually transformed into a technical documentation writer with her continuous research and development skills. She is an expert in C, C++, PHP, Python and RDBMS. She makes sure to evolve with technology. Thus, trained in BI, she is a Data Science enthusiast and is on the verge to pursue a career in Data Science.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

Featured Resources

Learn More

Please login to leave comments