<?php
// place PHP code here
?>
// — Denotes comments that only span one line
# — Another way of producing single-line comments
/*...*/ — Everything between /* and */ is not executed, also works across several lines
$firstName = 'Mike' # variables
function updateProduct() # function names
class ProductItem # class names
const ACCESS_KEY = '123abc'; # constants
echo 'Hello PHP';
# Debug output
var_dump($some_var);
print_r($products);
$name = 'Joe'; # string
$isActive = false; # boolean
$number = 32; # integer
$amount = 91.90; # floating-point
$GLOBALS
— Used to access global variables from anywhere inside a PHP script$_SERVER
— Contains information about the locations of headers, paths, and scripts$_GET
— Can collect data that was sent in the URL or submitted in an HTML form$_POST
— Used to gather data from an HTML form and to pass variables$_REQUEST
— Also collects data after submitting an HTML form
boolval
— Used to retrieve the boolean value of a variabledebug_zval_dump
— Outputs a string representation of an internal zend valueempty
— Checks whether a variable is empty or notfloatval
— Get the float value of a variable (doubleval is another possibility)get_defined_vars
— Returns an array of all defined variablesget_resource_type
— Returns the resource typegettype
— Retrieves the variable typeimport_request_variables
— Import GET/POST/Cookie variables into the global scopeintval
— Find the integer value of a variableis_array
— Checks whether a variable is an arrayis_bool
— Finds out if a variable is a booleanis_callable
— Verify whether you can call the contents of a variable as a functionis_countable
— Check whether the contents of a variable are countableis_float
— Find out if the type of a variable is float, alternatives: is_double and is_realis_int
— Check if the type of a variable is an integer, is_integer and is_long also worksis_iterable
— Verify that a variable’s content is an iterable valueis_null
— Checks whether a variable’s value is NULLis_numeric
— Find out if a variable is a number or a numeric stringis_object
— Determines whether a variable is an objectis_resource
— Check if a variable is a resourceis_scalar
— Tests if a variable is a scalaris_string
— Find out whether the type of a variable is a stringisset
— Determine if a variable has been set and is not NULLprint_r
— Provides human-readable information about a variableserialize
— Generates a representation of a value that is storablesettype
— Sets a variable’s typestrval
— Retrieves the string value of a variableunserialize
— Creates a PHP value from a stored representationunset
— Unsets a variablevar_dump
— Dumps information about a variablevar_export
— Outputs or returns a string representation of a variable that can be parsed
define(name, value, case_sensitive_true_false);
LINE
— Denotes the number of the current line in a fileFILE
— Is the full path and filename of the fileDIR
— The directory of the fileFUNCTION
— Name of the functionCLASS
— Class name, includes the namespace it was declared inTRAIT
— The trait name, also includes the namespaceMETHOD
— The class method nameNAMESPACE
— Name of the current namespace
+
— Addition-
— Subtraction*
— Multiplication/
— Division%
— Modulo (the remainder of value divided by another)**
— Exponentiation
+=
— a += b is the same as a = a + b-=
— a -= b is the same as a = a – b*=
— a *= b is the same as a = a * b/=
— a /= b is the same as a = a / b%=
— a %= b is the same as a = a % b
==
— Equal===
— Identical!=
— Not equal<>
— Not equal!==
— Not identical<
— Less than>
— Greater than<=
— Less than or equal to>=
— Greater than or equal to<=>
— Less than, equal to, or greater than
and
— Andor
— Orxor
— Exclusive or!
— Not&&
— And||
— Or
&
— And|
— Or (inclusive or)^
— Xor (exclusive or)~
— Not<<
— Shift left>>
— Shift right
The @ sign can be used to prevent expressions from generating error messages.
PHP supports one execution operator, which is `` (backticks). PHP will attempt to execute the contents of the backticks as a shell command.
++$v
— Increments a variable by one, then returns it$v++
— Returns a variable, then increments it by one--$v
— Decrements the variable by one, returns it afterward$v--
— Returns the variable then decrements it by one
.
— Used to concatenate (mean combine) arguments.=
— Used to append the argument on the right to the left-side argument
- Single quotes — This is the simplest way. Just wrap your text in ' markers and PHP will handle it as a string.
- Double quotes — As an alternative you can use ". When you do, it’s possible to use the escape characters below to display special characters.
- heredoc — Begin a string with <<< and an identifier, then put the string in a new line. Close it in another line by repeating the identifier. heredoc behaves like double-quoted strings.
- nowdoc — Is what heredoc is for double-quoted strings but for single quotes. It works the same way and eliminates the need for escape characters.
NOTE: Strings can contain variables, arrays, and objects.
# String concatenation
echo 'Hello ' . $name;
# String escape characters \n new line \t tab \\ backslash
echo "Hello Joe\nHello Jimmy";
# String interpolation
echo "Hello $name";
# String length
echo strlen($name);
# Remove space(s) before and after
echo trim($text);
# Convert to lowercase / uppercase
echo strtolower($email);
echo strtoupper($name);
# Converts the first character to uppercase
echo ucfirst($name); # 'Joe'
# Replace text c by text d in $text
echo str_replace('c', 'd', $text);
# String Contains (PHP 8)
echo str_contains($name, 'oe') # true
\n
— Linefeed\r
— Carriage return\t
— Horizontal tab\v
— Vertical tab\e
— Escape\f
— Form feed\
— Backslash$
— Dollar sign/'
— Single quote"
— Double quote[0-7]{1,3}
— Character in octal notation\x[0-9A-Fa-f]{1,2}
— Character in hexadecimal notation\u{[0-9A-Fa-f]+}
— String as UTF-8 representation
addcslashes
— Returns a string with backslashes in front of specified charactersaddslashes
— Returns a string with backslashes in front of characters that need to be escapedbin2hex
— Converts a string of ASCII characters to hexadecimal valueschop
— Removes space or other characters from the right end of a stringchr
— Returns a character from a specified ASCII valuechunk_split
— Splits a string into a series of smaller chunksconvert_cyr_string
— Converts a string from a Cyrillic character set to anotherconvert_uudecode
— Decodes a uuencoded stringconvert_uuencode
— Encodes a string using uuencodecount_chars
— Returns information about the characters in a stringcrc32
— Calculates a 32-bit CRC for a stringcrypt
— Returns a hashed stringecho or echo ''
— Outputs one or several stringsexplode
— Breaks down a string into an arrayfprintf
— Writes a formatted string to a specified output streamget_html_translation_table
— Returns the translation table used by htmlspecialchars() and htmlentities()hebrev
— Transforms Hebrew text to visual texthebrevc
— Converts Hebrew text to visual text and implements HTML line breakshex2bin
— Translate hexadecimal values to ASCII charactershtml_entity_decode
— Turns HTML entities to charactershtmlentities
— Converts characters to HTML entitieshtmlspecialchars_decode
— Transforms special HTML entities to charactershtmlspecialchars
— Switches predefined characters to HTML entitiesimplode
— Retrieves a string from the elements of an array, same as joinlcfirst
— Changes a string’s first character to lowercaselevenshtein
— Calculates the Levenshtein distance between two stringslocaleconv
— Returns information about numeric and monetary formatting for the localeltrim
— Removes spaces or other characters from the left side of a stringmd5
— Calculates the MD5 hash of a string and returns itmd5_file
— Calculates the MD5 hash of a filemetaphone
— Provides the metaphone key of a stringmoney_format
— Returns a string as a currency stringnl_langinfo
— Gives specific locale informationnl2br
— Inserts HTML line breaks for each new line in a stringnumber_format
— Formats a number including grouped thousandsord
— Returns the ASCII value of a string’s first characterparse_str
— Parses a string into variablesprint
— Outputs one or several stringsprintf
— Outputs a formatted stringquoted_printable_decode
— Converts a quoted-printable string to 8-bit binaryquoted_printable_encode
— Goes from 8-bit string to a quoted-printable stringquotemeta
— Returns a string with a backslash before metacharactersrtrim
— Strips whitespace or other characters from the right side of a stringsetlocale
— Sets locale informationsha1
— Calculates a string’s SHA-1 hashsha1_file
— Does the same for a filesimilar_text
— Determines the similarity between two stringssoundex
— Calculates the soundex key of a stringsprintf
— Returns a formatted stringsscanf
— Parses input from a string according to a specified formatstr_getcsv
— Parses a CSV string into an arraystr_ireplace
— Replaces specified characters in a string with specified replacements (case-insensitive)str_pad
— Pads a string to a specified lengthstr_repeat
— Repeats a string a preset number of timesstr_replace
— Replaces specified characters in a string (case-sensitive)str_rot13
— Performs ROT13 encoding on a stringstr_shuffle
— Randomly shuffles the characters in a stringstr_split
— Splits strings into arraysstr_word_count
— Returns the number of words in a stringstrcasecmp
— Case-insensitive comparison of two stringsstrcmp
— Binary safe string comparison (case sensitive)strcoll
— Compares two strings based on localestrcspn
— Returns the number of characters found in a string before the occurrence of specified charactersstrip_tags
— Removes HTML and PHP tags from a stringstripcslashes
— Opposite of addcslashes()stripslashes
— Opposite of addslashes()stripos
— Finds the position of the first occurrence of a substring within a string (case insensitive)stristr
— Case-insensitive version of strstr()strlen
— Returns the length of a stringstrnatcasecmp
— Case-insensitive comparison of two strings using a “natural order” algorithmstrnatcmp
— Same as the aforementioned but case sensitivestrncasecmp
— String comparison of a defined number of characters (case insensitive)strncmp
— Same as above but case-sensitivestrpbrk
— Searches a string for any number of charactersstrpos
— Returns the position of the first occurrence of a substring in a string (case sensitive)strrchr
— Finds the last occurrence of a string within another stringstrrev
— Reverses a stringstrripos
— Finds the position of the last occurrence of a string’s substring (case insensitive)strrpos
— Same as strripos but case sensitivestrspn
— The number of characters in a string with only characters from a specified liststrstr
— Case-sensitive search for the first occurrence of a string inside another stringstrtok
— Splits a string into smaller chunksstrtolower
— Converts all characters in a string to lowercasestrtoupper
— Same but for uppercase lettersstrtr
— Translates certain characters in a string, alternative: strchrsubstr
— Returns a specified part of a stringsubstr_compare
— Compares two strings from a specified start position up to a certain length, optionally case sensitivesubstr_count
— Counts the number of times a substring occurs within a stringsubstr_replace
— Replaces a substring with something elsetrim
— Removes space or other characters from both sides of a stringucfirst
— Transforms the first character of a string to uppercaseucwords
— Converts the first character of every word in a string to uppercasevfprintf
— Writes a formatted string to a specified output streamvprintf
— Outputs a formatted stringvsprintf
— Writes a formatted string to a variablewordwrap
— Shortens a string to a given number of characters
$ Check if numeric
echo is_numeric('12.99'); # true
$ Round a number
echo(round(0.75)); # returns 1
echo(round(0.40)); # returns 0
# Output a random number
echo(rand(10, 100)); # 32
# Ternary operator (true : false)
echo $isValid ? 'user valid' : 'user not valid';
# Null Coalesce Operator
echo $name ?? 'Joe'; # output 'Joe' if $name is null
# Null Coalesce Assignment
$name ??= 'Joe';
# Null Safe Operator (PHP 8) will return null if one ? is null
echo $user?->profile?->activate();
# Null Safe + Null Coalesce (if null will return 'No user profile')
echo $user?->profile?->activate() ?? 'Not applicable';
# Spaceship operator returns -1 0 1
$names = ['Mike', 'Paul', 'John']
usort($names, function($a, $b) {
return $a <=> $b;
}
# ['John', 'Mike', 'Paul']
# Will return false when convert as boolean
false, 0, 0.0, null, unset, '0', '', []
# Conditionals
if ($condition == 20) {
echo 'condition 20';
} elseif ($condition == 10) {
echo 'condition 10';
} else {
echo 'anything except 20 and 10';
}
# Everything on one line
if ($isActive) return true;
# Switch Statement
switch (n) {
case x:
code to execute if n=x;
break;
case y:
code to execute if n=y;
break;
case z:
code to execute if n=z;
break;
// add more cases as needed
default:
code to execute if n is neither of the above;
}
# Match Expression (PHP 8)
$type = match($color) {
'red' => 'danger',
'yellow', 'orange' => 'warning',
'green' => 'success',
default => 'unknown'
};
# for loop
for ($i = 0; $i < 20; $i++) {
echo "i value = " . i;
}
# while loop
$number = 1;
while ($num < 10) {
echo 'value : ' . $num;
$num += 1;
}
# do while
$num = 1;
do {
echo 'value : ' . $num;
$num += 1;
} while ($num < 10);
# foreach with break / continue example
$values = ['one', 'two', 'three'];
foreach ($values as $val) {
if ($val === 'two') {
break; # exit loop
} elseif ($val === 'three') {
continue; # next loop iteration
}
}
$languages = array("C++", "Java", "PHP");
echo "What is your favorite Language? Is it " . $languages[0] . ", " . $languages[1] . " or " . $languages[2] . "?";
- Indexed arrays – Arrays that have a numeric index
- Associative arrays – Arrays where the keys are named
- Multidimensional arrays – Arrays that contain one or more other arrays
# Array declaration
$names = ['Joe', 'James', 'Peter', 'Zeus'];
# Append to array
$names[] = 'Jessie';
# Array merge
$array3 = array_merge($array1, $array2);
# Array Concat with Spread Operator
$names = ['Joe', 'James', 'Peter'];
$people = ['John', ...$names]; // ['John', 'Joe', 'James', 'Peter'];
# Remove array entry
unset($names['Joe']);
# Array to string
echo implode(', ', $names) // output James, Peter
# String to Array
echo explode(',', $text);
# Direct access
echo $names[1] # output James
# Loop for each array entry
foreach($names as $name) {
echo 'Hello ' . $name;
}
# Number of items in a Array
echo count($names);
# Associative array:
$person = ['age' => 32, 'gender' => 'female'];
# Add to associative array:
$person['name'] = 'Amanda';
# Loop through associative array key => value:
foreach($names as $key => $value) {
echo $key . ' : ' . $value;
}
# Check if a specific key exist
echo array_key_exist('age', $person);
# Return keys
echo array_keys($person); # ['age', 'gender']
# Return values
echo array_values($person) # [32, 'female']
# Array filter (return a filtered array)
$filteredPeople = array_filter($people, function ($person) {
return $names->active;
})
# Array map (return transform array):
$onlyNames = array_map(function($person) {
return [‘name’ => $person->name];
}, $people);
# Search associative array
$items = [
['id' => '100', 'name' => 'product 1'],
['id' => '200', 'name' => 'product 2'],
['id' => '300', 'name' => 'product 3'],
['id' => '400', 'name' => 'product 4'],
];
# search all value in the 'name' column
$found_key = array_search('product 4', array_column($items, 'name'));
array_change_key_case
— Changes all keys in an array to uppercase or lowercasearray_chunk
— Splits an array into chunksarray_column
— Retrieves the values from a single column in an arrayarray_combine
— Merges the keys from one array and the values from another into a new arrayarray_count_values
— Counts all values in an arrayarray_diff
— Compares arrays, returns the difference (values only)array_diff_assoc
— Compares arrays, returns the difference (values and keys)array_diff_key
— Compares arrays, returns the difference (keys only)array_diff_uassoc
— Compares arrays (keys and values) through a user callback functionarray_diff_ukey
— Compares arrays (keys only) through a user callback functionarray_fill
— Fills an array with valuesarray_fill_keys
— Fills an array with values, specifying keysarray_filter
— Filters the elements of an array via a callback functionarray_flip
— Exchanges all keys in an array with their associated valuesarray_intersect
— Compare arrays and return their matches (values only)array_intersect_assoc
— Compare arrays and return their matches (keys and values)array_intersect_key
— Compare arrays and return their matches (keys only)array_intersect_uassoc
— Compare arrays via a user-defined callback function (keys and values)array_intersect_ukey
— Compare arrays via a user-defined callback function (keys only)array_key_exists
— Checks if a specified key exists in an array, alternative: key_existsarray_keys
— Returns all keys or a subset of keys in an arrayarray_map
— Applies a callback to the elements of a given arrayarray_merge
— Merge one or several arraysarray_merge_recursive
— Merge one or more arrays recursivelyarray_multisort
— Sorts of multiple or multi-dimensional arraysarray_pad
— Inserts a specified number of items (with a specified value) into an arrayarray_pop
— Deletes an element from the end of an arrayarray_product
— Calculate the product of all values in an arrayarray_push
— Push one or several elements to the end of the arrayarray_rand
— Pick one or more random entries out of an arrayarray_reduce
— Reduce the array to a single string using a user-defined functionarray_replace
— Replaces elements in the first array with values from following arraysarray_replace_recursive
— Recursively replaces elements from later arrays into the first arrayarray_reverse
— Returns an array in reverse orderarray_search
— Searches the array for a given value and returns the first key if successfularray_shift
— Shifts an element from the beginning of an arrayarray_slice
— Extracts a slice of an arrayarray_splice
— Removes a portion of the array and replaces itarray_sum
— Calculate the sum of the values in an arrayarray_udiff
— Compare arrays and return the difference using a user function (values only)array_udiff_assoc
— Compare arrays and return the difference using default and a user function (keys and values)array_udiff_uassoc
— Compare arrays and return the difference using two user functions (values and keys)array_uintersect
— Compare arrays and return the matches via user function (values only)array_uintersect_assoc
— Compare arrays and return the matches via a default user function (keys and values)array_uintersect_uassoc
— Compare arrays and return the matches via two user functions (keys and values)array_unique
— Removes duplicate values from an arrayarray_unshift
— Adds one or more elements to the beginning of an arrayarray_values
— Returns all values of an arrayarray_walk
— Applies a user function to every element in an arrayarray_walk_recursive
— Recursively applies a user function to every element of an arrayarsort
— Sorts an associative array in descending order according to the valueasort
— Sorts an associative array in ascending order according to the valuecompact
— Create an array containing variables and their valuescount
— Count all elements in an array, alternatively use sizeofcurrent
— Returns the current element in an array, an alternative is poseach
— Return the current key and value pair from an arrayend
— Set the internal pointer to the last element of an arrayextract
— Import variables from an array into the current symbol tablein_array
— Checks if a value exists in an arraykey
— Fetches a key from an arraykrsort
— Sorts an associative array by key in reverse orderksort
— Sorts an associative array by keylist
— Assigns variables as if they were an arraynatcasesort
— Sorts an array using a “natural order” algorithm independent of casenatsort
— Sorts an array using a “natural order” algorithmnext
— Advance the internal pointer of an arrayprev
— Move the internal array pointer backwardrange
— Creates an array from a range of elementsreset
— Set the internal array pointer to its first elementrsort
— Sort an array in reverse ordershuffle
— Shuffle an arraysort
— Sorts an indexed array in ascending orderuasort
— Sorts an array with a user-defined comparison functionuksort
— Arrange an array by keys using a user-defined comparison functionusort
— Categorize an array by values using a comparison function defined by the user
# Function declaration
function name($firstName, $lastName = 'defaultvalue') {
return "$firstName $lastName"
}
# Function call
name('John', 'Smith');
# Function call with named parameters (PHP 8)
name(firstName: 'John', lastName: 'Smith'); # order can change
# Function variables params
function name(...$params) {
return $params[0] . “ “ . params[1];
}
# Closure function
Route::get('/', function () {
return view('welcome');
});
# Arrow functions
Route::get('/', fn () => view('welcome');
# Open a file to read
$file = fopen("foo.txt", "r");
# Output lines until EOF is reached
while(! feof($file)) {
$line = fgets($file);
echo $line. "<br>";
}
fclose($file);
# File write
$file = fopen('test.csv', 'a');
$array = ['name' => 'Mike', 'age' => 45];
# Write key name as csv header
fputcsv($file, array_keys($array[0]));
# Write lines (format as csv)
foreach ($array as $row) {
fputcsv($file, $row);
}
fclose($file);
# Throw an error
if (someCondition) {
throw new Exception('error');
}
# Catch the Error
try {
$obj->check($data);
} catch (Exception $e) {
echo $e->getMessage();
}
debug_backtrace
— Used to generate a backtracedebug_print_backtrace
— Prints a backtraceerror_get_last
— Gets the last error that occurrederror_log
— Sends an error message to the web server’s log, a file or a mail accounterror_reporting
— Specifies which PHP errors are reportedrestore_error_handler
— Reverts to the previous error handler functionrestore_exception_handler
— Goes back to the previous exception handlerset_error_handler
— Sets a user-defined function to handle script errorsset_exception_handler
— Sets an exception handler function defined by the usertrigger_error
— Generates a user-level error message, you can also useuser_error()
E_ERROR
— Fatal run-time errors that cause the halting of the script and can’t be recovered fromE_WARNING
— Non-fatal run-time errors, execution of the script continuesE_PARSE
— Compile-time parse errors, should only be generated by the parserE_NOTICE
— Run-time notices that indicate a possible errorE_CORE_ERROR
— Fatal errors at PHP initialization, like anE_ERROR
in PHP coreE_CORE_WARNING
— Non-fatal errors at PHP startup, similar toE_WARNING
but in PHP coreE_COMPILE_ERROR
— Fatal compile-time errors generated by the Zend Scripting EngineE_COMPILE_WARNING
— Non-fatal compile-time errors by the Zend Scripting EngineE_USER_ERROR
— Fatal user-generated error, set by the programmer usingtrigger_error()
E_USER_WARNING
— Non-fatal user-generated warningE_USER_NOTICE
— User-generated notice bytrigger_error()
E_STRICT
— Suggestions by PHP to improve your code (needs to be enabled)E_RECOVERABLE_ERROR
— Catchable fatal error caught by a user-defined handleE_DEPRECATED
— Enable this to receive warnings about a code which is not future-proofE_USER_DEPRECATED
— User-generated warning for deprecated codeE_ALL
— All errors and warnings exceptE_STRICT
# Basic class declaration
class Person {
# ...
}
# object instantiation
$user = new User
# Class properties and constructor
class User {
protected $userName;
protected $userId;
public function __construct($userName, $userId) {
$this->userName = $firstName;
$this->userId = $userId
}
# Constructor Property Promotion (PHP 8)
class User {
public function __construct(protected $userName, protected $userId) {
# ...
}
# Static constructor
public static function create(...$params) {
return new self($params)
}
$user = User::create(‘Joe Smith’, ‘jsmith1982’);
# Class inheritance
class SuperUser extends User {
public function username() {
parent::username();
echo 'Override method';
}
}
# Static Method
class HelloWorld {
public static function hello() {
echo "Hello World!";
}
}
# Call static method
HelloWorld::hello();
# Static method internal call
class HelloWorld {
public static function hello() {
echo "Hello World!";
}
public function __construct() {
self::hello();
}
}
new HelloWorld();
# Interfaces
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo "ruff!!!";
}
}
$animal = new Dog();
$animal->makeSound();
# Trait (mix-in)
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
class Greetings {
use HelloWorld;
}
$object = new Greetings();
$object->sayHello();
PHP has the ability to manipulate data sent to the browser from the webserver.
header
— Sends a raw HTTP header to the browserheaders_list
— A list of response headers ready to send (or already sent)headers_sent
— Checks if and where the HTTP headers have been sentsetcookie
— Defines a cookie to be sent along with the rest of the HTTP headerssetrawcookie
— Defines a cookie (without URL encoding) to be sent along
Many platforms that are based on PHP work with a MySQL database in the background.
mysqli_affected_rows
— The number of affected rows in the previous MySQL operationmysqli_autocommit
— Turn auto-committing database modifications on or offmysqli_change_user
— Changes the user of the specified database connectionmysqli_character_set_name
— The default character set for the database connectionmysqli_close
— Closes an open database connectionmysqli_commit
— Commits the current transactionmysqli_connect_errno
— The error code from the last connection errormysqli_connect_error
— The error description from the last connection errormysqli_connect
— Opens a new connection to the MySQL servermysqli_data_seek
— Moves the result pointer to an arbitrary row in the result setmysqli_debug
— Performs debugging operationsmysqli_dump_debug_info
— Dumps debugging information into a logmysqli_errno
— The last error code for the most recent function callmysqli_error_list
— A list of errors for the most recent function callmysqli_error
— The last error description for the most recent function callmysqli_fetch_all
— Fetches all result rows as an arraymysqli_fetch_array
— Fetches a result row as an associative, a numeric array, or bothmysqli_fetch_assoc
— Fetches a result row as an associative arraymysqli_fetch_field_direct
— Metadata for a single field as an objectmysqli_fetch_field
— The next field in the result set as an objectmysqli_fetch_fields
— An array of objects that represent the fields in a result setmysqli_fetch_lengths
— The lengths of the columns of the current row in the result setmysqli_fetch_object
— The current row of a result set as an objectmysqli_fetch_row
— Fetches one row from a result set and returns it as an enumerated arraymysqli_field_count
— The number of columns for the most recent querymysqli_field_seek
— Sets the field cursor to the given field offsetmysqli_field_tell
— The position of the field cursormysqli_free_result
— Frees the memory associated with a resultmysqli_get_charset
— A character set objectmysqli_get_client_info
— The MySQL client library versionmysqli_get_client_stats
— Returns client per-process statisticsmysqli_get_client_version
— The MySQL client library version as an integermysqli_get_connection_stats
— Statistics about the client connectionmysqli_get_host_info
— The MySQL server hostname and the connection typemysqli_get_proto_info
— The MySQL protocol versionmysqli_get_server_info
— Returns the MySQL server versionmysqli_get_server_version
— The MySQL server version as an integermysqli_info
— Returns information about the most recently executed querymysqli_init
— Initializes MySQLi and returns a resource for use with mysqli_real_connect()mysqli_insert_id
— Returns the auto-generated ID used in the last querymysqli_kill
— Asks the server to kill a MySQL threadmysqli_more_results
— Checks if there are more results from a multi-querymysqli_multi_query
— Performs one or more queries on the databasemysqli_next_result
— Prepares the next result set from mysqli_multi_query()mysqli_num_fields
— The number of fields in a result setmysqli_num_rows
— The number of rows in a result setmysqli_options
— Sets extra connect options and affect behavior for a connectionmysqli_ping
— Pings a server connection or tries to reconnect if it has gone downmysqli_prepare
— Prepares an SQL statement for executionmysqli_query
— Performs a query against the databasemysqli_real_connect
— Opens a new connection to the MySQL servermysqli_real_escape_string
— Escapes special characters in a string for use in an SQL statementmysqli_real_query
— Executes an SQL querymysqli_reap_async_query
— Returns the result from async querymysqli_refresh
— Refreshes tables or caches or resets the replication server informationmysqli_rollback
— Rolls back the current transaction for the databasemysqli_select_db
— Changes the default database for the connectionmysqli_set_charset
— Sets the default client character setmysqli_set_local_infile_default
— Unsets a user-defined handler for the LOAD LOCAL INFILE commandmysqli_set_local_infile_handler
— Sets a callback function for the LOAD DATA LOCAL INFILE commandmysqli_sqlstate
— Returns the SQLSTATE error code for the last MySQL operationmysqli_ssl_set
— Establishes secure connections using SSLmysqli_stat
— The current system statusmysqli_stmt_init
— Initializes a statement and returns an object for use with mysqli_stmt_prepare()mysqli_store_result
— Transfers a result set from the last querymysqli_thread_id
— The thread ID for the current connectionmysqli_thread_safe
— Returns if the client library is compiled as thread-safemysqli_use_result
— Initiates the retrieval of a result set from the last query executed using the mysqli_real_query()mysqli_warning_count
— The number of warnings from the last query in the connection
PHP has a number of date/time related functions.
checkdate
— Checks the validity of a Gregorian datedate_add
— Adds a number of days, months, years, hours, minutes and seconds to a date objectdate_create_from_format
— Returns a formatted DateTime objectdate_create
— Creates a new DateTime objectdate_date_set
— Sets a new datedate_default_timezone_get
— Returns the default timezone used by all functionsdate_default_timezone_set
— Sets the default timezonedate_diff
— Calculates the difference between two datesdate_format
— Returns a date formatted according to a specific formatdate_get_last_errors
— Returns warnings or errors found in a date stringdate_interval_create_from_date_string
— Sets up a DateInterval from relative parts of a stringdate_interval_format
— Formats an intervaldate_isodate_set
— Sets a date according to ISO 8601 standardsdate_modify
— Modifies the timestampdate_offset_get
— Returns the offset of the timezonedate_parse_from_format
— Returns an array with detailed information about a specified date, according to a specified formatdate_parse
— Returns an array with detailed information about a specified datedate_sub
— Subtracts days, months, years, hours, minutes and seconds from a datedate_sun_info
— Returns an array containing information about sunset/sunrise and twilight begin/end for a specified day and locationdate_sunrise
— The sunrise time for a specified day and locationdate_sunset
— The sunset time for a specified day and locationdate_time_set
— Sets the timedate_timestamp_get
— Returns the Unix timestampdate_timestamp_set
— Sets the date and time based on a Unix timestampdate_timezone_get
— Returns the time zone of a given DateTime objectdate_timezone_set
— Sets the time zone for a DateTime objectdate
— Formats a local date and timegetdate
— Date/time information of a timestamp or the current local date/timegettimeofday
— The current timegmdate
— Formats a GMT/UTC date and timegmmktime
— The Unix timestamp for a GMT dategmstrftime
— Formats a GMT/UTC date and time according to locale settingsidate
— Formats a local time/date as an integerlocaltime
— The local timemicrotime
— The current Unix timestamp with microsecondsmktime
— The Unix timestamp for a datestrftime
— Formats a local time and/or date according to locale settingsstrptime
— Parses a time/date generated with strftimestrtotime
— Transforms an English textual DateTime into a Unix timestamptime
— The current time as a Unix timestamptimezone_abbreviations_list
— Returns an array containing dst, offset, and the timezone nametimezone_identifiers_list
— An indexed array with all timezone identifierstimezone_location_get
— Location information for a specified timezonetimezone_name_from_abbr
— Returns the timezone name from an abbreviationtimezone_name_get
— The name of the timezonetimezone_offset_get
— The timezone offset from GMTtimezone_open
— Creates a new DateTimeZone objecttimezone_transitions_get
— Returns all transitions for the timezonetimezone_version_get
— Returns the version of the timezonedb
d
— 01 to 31j
— 1 to 31D
— Mon through Sunl
— Sunday through SaturdayN
— 1 (for Mon) through 7 (for Sat)w
— 0 (for Sun) through 6 (for Sat)m
— Months, 01 through 12n
— Months, 1 through 12F
— January through DecemberM
— Jan through DecY
— Four digits year (e.g. 2018)y
— Two digits year (e.g. 18)L
— Defines whether it’s a leap year (1 or 0)a
— am and pmA
— AM and PMg
— Hours 1 through 12h
— Hours 01 through 12G
— Hours 0 through 23H
— Hours 00 through 23i
— Minutes 00 to 59s
— Seconds 00 to 59
$expr = "/pattern/i";
preg_match
- Returns 1 if the pattern was found in the string and 0 if notpreg_match_all
- Returns the number of times the pattern was found in the string, which may also be 0preg_replace
- Returns a new string where matched patterns have been replaced with another string
i
- Performs a case-insensitive searchm
- Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)u
- Enables correct matching of UTF-8 encoded patterns
[abc]
– Find one character from the options between the brackets[^abc]
– Find any character NOT between the brackets[0-9]
– Find one character from the range 0 to 9
|
- Find a match for any one of the patterns separated by | as in: cat|dog|fish.
- Find just one instance of any character^
- Finds a match as the beginning of a string as in: ^Hello$
- Finds a match at the end of the string as in: World$\d
- Find a digit\s
- Find a whitespace character\b
- Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b\uxxxx
- Find the Unicode character specified by the hexadecimal number xxxx
n+
- Matches any string that contains at least one nn*
- Matches any string that contains zero or more occurrences of nn?
- Matches any string that contains zero or one occurrences of nn{x}
- Matches any string that contains a sequence of X n’sn{x,y}
- Matches any string that contains a sequence of X to Y n’sn{x,}
- Matches any string that contains a sequence of at least X n’s
You can use parentheses ( ) to apply quantifiers to entire patterns. They can also be used to select parts of the pattern to be used as a match.
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // Outputs 1
Filters are used to validate and filter data that is coming from insecure sources.
filter_has_var
— Checks if a variable of the specified type existsfilter_id
— Returns the ID belonging to a named filterfilter_input
— Retrieves a specified external variable by name and optionally filters itfilter_input_array
— Pulls external variables and optionally filters themfilter_list
— Returns a list of all supported filtersfilter_var_array
— Gets multiple variables and optionally filters themfilter_var
— Filters a variable with a specified filter
FILTER_VALIDATE_BOOLEAN
— Validates a booleanFILTER_VALIDATE_EMAIL
— Certifies an e-mail addressFILTER_VALIDATE_FLOAT
— Confirms a floatFILTER_VALIDATE_INT
— Verifies an integerFILTER_VALIDATE_IP
— Validates an IP addressFILTER_VALIDATE_REGEXP
— Confirms a regular expressionFILTER_VALIDATE_URL
— Validates a URLFILTER_SANITIZE_EMAIL
— Removes all illegal characters from an e-mail addressFILTER_SANITIZE_ENCODED
— Removes/Encodes special charactersFILTER_SANITIZE_MAGIC_QUOTES
— Applies addslashes()FILTER_SANITIZE_NUMBER_FLOAT
— Removes all characters, except digits, +- and .,eEFILTER_SANITIZE_NUMBER_INT
— Gets rid of all characters except digits and + –FILTER_SANITIZE_SPECIAL_CHARS
— Removes special charactersFILTER_SANITIZE_FULL_SPECIAL_CHARS
— Converts special characters to HTML entitiesFILTER_SANITIZE_STRING
— Removes tags/special characters from a string, alternative:FILTER_SANITIZE_STRIPPED
FILTER_SANITIZE_URL
— Rids all illegal characters from a URLFILTER_UNSAFE_RAW
—Do nothing, optionally strip/encode special charactersFILTER_CALLBACK
— Call a user-defined function to filter data