PHP Cheat Sheet - 2021 Edition
Hypertext Preprocessor (PHP) is a common scripting language used for app development. PHP gets frequently updated, so it remains well-maintained and therefore attractive to those wanting a language that adapts to the developing IT world. That’s one reason we have a coding bootcamp, as languages like PHP remain popular to developers and employers. Connect with our experts to learn more about our Web Development Bootcamp.
The following PHP cheat sheet can help you review basic commands, such as before you take a PHP exam. However, since it’s a language, this guide is simply a list of the commands, and more commands can be further explained through other cheat sheets found online.
PHP Basic Commands
Including PHP in a File
<?php // place PHP code here ?>
Writing Comments
//
Indicates comments that span on one line only
#
Alternate path of producing single-line comments
/*...*/
Everything within /* and */ will not be executed, and this works across
multiple lines
Outputting Data
<?php echo "<h1>PHP Cheat Sheet</h1>"; ?>
Writing PHP Functions
function NameOfTheFunction() {
//place PHP code here
}
VARIABLES AND CONSTANTS
Defining Variables
<?php
$BlogPostTitle = "PHP Cheat Sheet";
?>
Data Types
Integers
Integers are non-decimal numbers within -2,147,483,648 and 2,147,483,647. They must be at least one digit and no decimal point. It can be in decimal, hexadecimal or octal.
Floats
Name for numbers with a decimal point or in exponential form.
Strings
Strings mean text. These are discussed below.
Boolean values
These are true/false statements.
Arrays
Arrays are variables that store several values. These will be discussed in detail later on.
Objects
Objects store both data as well as information on how to process the data.
Resources
Resources are references to functions and additional resources outside of PHP.
NULL
NULL means the variable doesn’t have any value.
Variable Scope
function myFunction() {
global $a, $b;
$b = $a - $b; }
Predefined Variables
$GLOBALS
Globals accesses global variables from anywhere inside a PHP script.
$_SERVER
Server contains information about where headers, paths and scripts are located.
$_GET
GET collects data that was sent in the URL or submitted in an HTML form.
$_POST
POST is used to collect data from an HTML form and to pass variables.
$_REQUEST
REQUEST collects data after submitting an HTML form.
Variable-handling Functions
boolval
This will retrieve the boolean value of a variable.
debug_zval_dump
This outputs a string representation of an internal zend value.
empty
Empty finds if a variable is empty or not.
floatval
This finds the float value of a variable (doubleval can also be used).
get_defined_vars
This will return an array of all defined variables.
get_resource_type
Returns the resource type.
gettype
Retrieves the variable type.
import_request_variables
Import GET/POST/Cookie variables into the global scope.
intval
Finds the integer value of a variable.
is_array
Checks if a variable is an array.
is_bool
Decides whether a variable is a boolean of 538 is_callable
Finds out if you can call the contents of a variable as a function.
is_countable
Decides if the contents of a variable are countable.
is_float
Decides if the variable type is float. You can also use: is_double and is_real
is_int
Finds if the type of a variable is an integer, and is_integer and is_long can also work.
is_iterable
Confirm if a variable’s content is an iterable value.
is_null
Confirms if a variable’s value is NULL
is_numeric
Discovers if a variable is a number or a numeric string
is_object
Finds if a variable is an object.
is_resource
Checks whether a variable is a resource.
is_string
Confirms if the type of a variable is a string
isset
Finds if a variable has been set and is not NULL
print_r
Provides human-readable info about a variable
serialize
Makes a representation of a value that is storable
settype
Sets a variable’s type
strval
Retrieves the string value of a variable
unserialize
Produces a PHP value from a stored representation
unset
Unsets a variable
var_dump
Dumps info about a variable
var_export
Returns a string representation of a variable that can be parsed
Constants
define(name, value, true/false)
Default PHP constants:
__LINE__
Denotes the number of the current line in a file
__FILE__
FILE is the full path and filename of the file
__DIR__
The directory of the file
__FUNCTION__
The function’s name
__CLASS__
Class name, also includes namespace it was declared in
__TRAIT__
The trait name, also includes the namespace
__METHOD__
The class method name
__NAMESPACE__
Name of the current namespace
PHP Arrays: Grouped Values
Indexed arrays
Arrays with a numeric index
Associative arrays
Arrays with named keys
Multidimensional arrays
Arrays that include one or more other arrays
Declaring an Array in PHP
<?php
$cms = array("WordPress", "Joomla", "Drupal");
echo "What is your favorite CMS? Is it " . $cms[0] . ", " .
$cms[1] . " or " . $cms[2] . "?";
?>
Array Functions
array_change_key_case
Changes all keys in an array to lowercase or uppercase
array_chunk
Cuts an array into chunks
array_column
Finds the values from a single column in an array
array_combine
Merges the keys from one array and the values from another into a new array
array_count_values
Counts all values in an array
array_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 function
array_diff_ukey
Compares arrays (keys only) through a user callback function
array_fill
This will fill an array with values
array_fill_keys
Fills an array with values, specifying keys
array_filter
Filters the elements of an array via a callback function
array_flip
Exchanges all the keys in an array with their associated values
array_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_exists
array_keys
Returns all keys or a subset of keys in an array
array_map
Applies a callback to the elements of a given array
array_merge
Combine one or more arrays
array_merge_recursive
Combine one or more arrays recursively
array_multisort
Sorts multiple or multi-dimensional arrays
array_pad
Inserts a specified number of items (with a specified value) into an array
array_pop
Deletes an element from the end of an array
array_product
Calculate the product of all values in an array
array_push
Push one or several elements to the end of the array
array_rand
Pick one or more random entries out of an array
array_reduce
Reduce the array to a single string using a user-defined function
array_replace
Replaces elements in the first array with values from following arrays
array_replace_recursive
Recursively replaces elements from later arrays into the first array
array_reverse
Returns an array in reverse order
array_search
Searches the array for a given value and returns the first key if successful
array_shift
Moves an element from the beginning of an array
array_slice
Extracts a slice of an array
array_splice
Deletes a portion of the array and replaces it
array_sum
Calculate the sum of the values in an array
array_udiff
Compare arrays and return the difference using a user function (values only)
array_udiff_assoc
Compare arrays and return the difference using a 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 array
array_unshift
Adds one or more elements to the beginning of an array
array_values
Returns all values of an array
array_walk
Applies a user function to every element in an array
array_walk_recursive
Recursively applies a user function to every element of an array
arsort
Sorts an associative array in descending order based on the value
asort
Sorts an associative array in ascending order according to the value
compact
Make an array containing variables and their values
count
Count all elements in an array, you can also use sizeof
current
Returns the current element in an array, you can also use poseach
Return the current key and value pair from an array
end
Set the internal pointer to the last element of an array
extract
Import variables from an array into the current symbol table
in_array
Checks if a value exists in an arraykey. Fetches a key from an array
krsort
Sorts an associative array by key in reverse order
ksort
Sorts an associative array by key
list
Assigns variables as if they were an array
natcasesort
Sorts an array using a “natural order” algorithm independent of case
natsort
Sorts an array using a “natural order” algorithm
next
Advance the internal pointer of an array
prev
Move the internal array pointer backwards
range
Produces an array from a range of elements
reset
Set the internal array pointer to its first element
rsort
Sort an array in reverse order
shuffle
Shuffle an array
sort
Sorts an indexed array in ascending order
uasort
Sorts an array with a user-defined comparison function
uksort
Arrange an array by keys using a user-defined comparison function
usort
Categorize an array by values using a comparison function defined by the user
PHP STRINGS
Define Strings
Single quotes
Wrap the text in ' markers and PHP will handle it as a string.
Double quotes
Double quotes can do the same thing.
heredoc
Begin a string with <<< and an identifier. Then you can put the string in a new line. Close it by repeating the identifier.
heredoc acts like double-quoted strings.
nowdoc
heredoc is similar to single quotes. It works similarly and gets rid of the need for escape characters.
Escape Characters
\n — Line feed
\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}
\x[0-9A-Fa-f]{1,2}
\u{[0-9A-Fa-f]+}
String Functions
addcslashes()
— Character in octal notation
— Character in hexadecimal notation
— String as UTF-8 representation
Returns a string with backslashes in front of specified characters
addslashes()
Returns a string with backslashes in front of characters that need to be escaped
bin2hex()
Changes a string of ASCII characters to hexadecimal values
chop()
Deletes space or other characters from the right end of a string
chr()
Returns a character from a specified ASCII value
chunk_split()
Splits a string into a series of smaller chunks
convert_cyr_string()
Changes 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 string
crc32()
Calculates a 32-bit CRC for a string
crypt()
Returns a hashed string
echo() or echo ''
Outputs one or several strings
explode()
Breaks down a string into an array
fprintf()
Writes a formatted string to a specified output stream
get_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 breaks
hex2bin()
Translate hexadecimal values to ASCII characters
html_entity_decode()
Turns HTML entities to characters
htmlentities()
Converts characters to HTML entities
htmlspecialchars_decode()
Transforms special HTML entities to characters
htmlspecialchars()
Switches predefined characters to HTML entities
implode()
Retrieves a string from the elements of an array, same as join()
lcfirst()
Changes a string’s first character to lowercase
levenshtein()
Calculates the Levenshtein distance between two strings
localeconv()
Returns information about numeric and monetary formatting for the locale
ltrim()
Removes spaces or other characters from the left side of a string
md5()
Calculates the MD5 hash of a string and returns it
md5_file()
Calculates the MD5 hash of a file
metaphone()
Provides the metaphone key of a string
money_format()
Returns a string as a currency string
nl_langinfo()
Gives specific locale information
nl2br()
Inserts HTML line breaks for each new line in a string
number_format()
Formats a number including grouped thousands
ord()
Returns the ASCII value of a string’s first character
parse_str()
Parses a string into variables
print()
Returns one or several strings
printf()
Outputs a formatted string
quoted_printable_decode()
Converts a quoted-printable string to 8-bit binary
quoted_printable_encode()
Goes from 8-bit string to a quoted-printable string
quotemeta()
Returns a string with a backslash before metacharacters
rtrim()
Strips whitespace or other characters from the right side of a string
setlocale()
Sets locale information
sha1()
Calculates a string’s SHA-1 hash
sha1_file()
Does the same for a file
similar_text()
Determines the similarity between two strings
soundex()
Calculates the soundex key of a string
sprintf()
Returns a formatted string
sscanf()
Parses input from a string according to a specified format
str_getcsv()
Parses a CSV string into an array
str_ireplace()
Replaces specified characters in a string with specified replacements (case-insensitive)
str_pad()
Pads a string to a specified length
str_repeat()
Repeats a string a preset number of times
str_replace()
Replaces certain characters in a string (case-sensitive)
str_rot13()
Performs ROT13 encoding on a string
str_shuffle()
Randomly shuffles the characters in a string
str_split()
Splits strings into arrays
str_word_count()
Returns the number of words in a string
strcasecmp()
Case-insensitive comparison of two strings
strcmp()
Binary safe string comparison (case sensitive)
strcoll()
Compares two strings based on locale
strcspn()
Returns the number of characters found in a string before the occurrence of specified characters
strip_tags()
Removes HTML and PHP tags from a string
stripcslashes()
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 string
strnatcasecmp()
Case-insensitive comparison of two strings using a “natural order” algorithm
strnatcmp()
Same as the aforementioned but case sensitive
strncasecmp()
String comparison of a defined number of characters (case insensitive)
strncmp()
Same as above but case-sensitive
strpbrk()
Searches a string for any number of characters
strpos()
Returns the position of the first occurrence of a substring in a string (case sensitive)
strrchr()
Discovers the last occurrence of a string within another string
strrev()
Reverses a string
strripos()
Finds the position of the last occurrence of a string’s substring (case insensitive)
strrpos()
Same as strripos() but case sensitive
strspn()
Number of characters in a string with only characters from a specified list
strstr()
Case-sensitive search for the first occurrence of a string inside another string
strtok()
Splits a string into smaller chunks
strtolower()
Converts all characters in a string to lowercase
strtoupper()
Same but for uppercase letters
strtr()
Translates certain characters in a string, alternative: strchr()
substr()
Returns a specified part of a string
substr_compare()
Compares two strings from a specified start position up to a certain length, optionally case sensitive
substr_count()
Counts the number of times a substring occurs within a string
substr_replace()
Replaces a substring with something else
trim()
Deletes space or other characters from both sides of a string
ucfirst()
Transforms the first character of a string to uppercase
ucwords()
Converts the first character of every word in a string to uppercase
vfprintf()
Writes a formatted string to a specified output stream
vprintf()
Outputs a formatted string
vsprintf()
Writes a formatted string to a variable
wordwrap()
Shortens a string to a given number of characters
PHP OPERATORS
Arithmetic Operators
+ — Addition
- — Subtraction
* — Multiplication
/ — Division
% — Modulo (the remainder of value divided by another) ** — Exponentiation
Assignment Operators
+= —a+=bisthesameasa=a+b -= —a-=bisthesameasa=a–b *= —a*=bisthesameasa=a*b /= —a/=bisthesameasa=a/b %= —a%=bisthesameasa=a%b
Comparison Operators
== — Equal
=== —Identical
!= — Not equal
<> — Not equal
!== —Notidentical
< — Less than
> — Greater than
<= — Less than or equal to
>= — Greater than or equal to
<=> —Lessthan,equalto,orgreaterthan
Logical Operators
and —And
or —Or
xor —Exclusiveor ! —Not
&& —And
|| —Or
Bitwise Operators
& —And
| — Or (inclusive or) ^ — Xor (exclusive or) ~ —Not
<< — Shift left
>> — Shift right
Error Control Operator
The @ sign can be used to prevent expressions from creating error messages, which is good for security reasons.
Execution Operator
PHP supports only one execution operator, which are `` (backticks). They are sometimes confused with single quotes, so be wary of this slight and common mistake. PHP tries to execute the contents of the backticks as a shell command.
Increment/Decrement Operators
++$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
String Operators
.
Used to concatenate (or combine) arguments
.=
Used to append the argument on the right to the left-side argument
LOOPS IN PHP
For Loop
for (starting counter value; ending counter value; increment by which
to increase) {
// code to execute goes here
}
Foreach Loop
foreach ($InsertYourArrayName as $value) {
// code to execute goes here
}
While Loop
while (condition that must apply) {
// code to execute goes here
}
Do..While Loop
do {
// code to execute goes here;
} while (condition that must apply);
CONDITIONAL STATEMENTS IN PHP
If Statement
if (condition) {
// code to execute if condition is met
}
If..Else
if (condition) {
// code to execute if condition is met
} else {
// code to execute if condition is not met
}
If..Elseif..Else
if (condition) {
// code to execute if condition is met
} elseif (condition) {
// code to execute if this condition is met
} else {
// code to execute if none of the conditions are met
}
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;
}
Web Development Training
We hope you found this short PHP cheat sheet. Enroll in our coding bootcamp to learn more about other popular languages that can help you further your career in IT. Connect with our experts to learn more about our Web Development Bootcamp.