A PHP cheat sheet (reference page)

PHP cheat sheet FAQ: Can you share a PHP cheat sheet?

This page is a PHP cheat sheet, but a different kind of cheat sheet. As I go deeper and deeper down the PHP rabbit hole, I found that instead of an over-simplified PHP cheat sheet, I wanted a "starter" page that will point me in the right direction when I'm looking for a PHP function for a task. For instance, if I can't remember how to add an element to a PHP array, I want to be able to search this page and find that easily.

I'm also adding links to this page, so I can find even more things very easily. For instance, working with arrays in PHP is a big deal, so I've added a link to a main PHP arrays reference page.

Given that brief introduction, here is my PHP cheat sheet (reference page).

This page is sponsored by Mat-Su Valley Programming - Alaska computer programming services

want to sponsor a page? learn more.

PHP if/else syntax (elseif)

Here are a few examples of correct PHP if/else syntax.

if ($a > $b) 
{
  echo "a is bigger than b";
}
elseif ($a == $b)
{
  echo "a is equal to b";
}
else
{
  echo "a is smaller than b";
}

You can also use this PHP if/elsif syntax:

if($a > $b):
  echo $a." is greater than ".$b;
elseif($a == $b): // Note the combination of the words.
  echo $a." equals ".$b;
else:
  echo $a." is neither greater than or equal to ".$b;
endif;

These examples come from php.net/manual/en/control-structures.elseif.php

PHP for loop syntax (for loop, foreach loop)

Here is an example of the PHP for loop syntax.

# get the array length
$length = count($words);
for ($i=0; $i<$length; $i++)
{
  $words[$i] = strtolower($words[$i]);
}

Here is an example of the PHP foreach loop syntax.

foreach ($words as $word)
{
  echo "$word\n";
}

PHP arrays reference

http://www.php.net/manual/en/ref.array.php

array_merge (array1, array2, ...)
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
array_pop (array)
Pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.
array_push (array, $var)
Treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.
array_rand (array)
Useful when you want to pick one or more random entries out of an array.
array_search (mixed $needle, array $haystack)
Searches haystack for needle.
array_diff
Compares array1 against array2 and returns the difference.
count
Counts all elements in an array, or properties in an object.
in_array (mixed $needle, array $haystack)
Searches haystack for needle.
key (array)
key() returns the index element of the current array position.
sort
Sorts an array. Elements will be arranged from lowest to highest when this function has completed.

PHP string functions

See this page for more information: http://www.php.net/manual/en/ref.strings.php

addslashes (string)
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
chop
An alias of rtrim. This is different than the Perl chop function.
crypt
One-way string hashing. return a hashed string using the standard Unix DES-based algorithm or alternative algorithms.
echo
Output one or more strings.
explode(string $delimiter, string $string, [, int $limit])
Spit a string into an array. Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
implode(string $glue, array $pieces), or implode(array $pieces)
Join array elements together into a string with a glue string. (Converts an array to a string.)
join
An alias of implode.
lcfirst ($str)
Returns a string with the first character of str converted to lowercase, if that character is alphabetic.
ltrim
Strip whitespace (or other characters) from the beginning of a string.
md5
Calculate the md5 hash of a string.
print
print() is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.
printf
Print a formatted string.
rtrim
Returns a string with whitespace stripped from the end of str.
sscanf
The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format, which is described in the documentation for sprintf().
sprintf
Returns a string produced according to the formatting string format.
str_replace
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
str_split
Converts a string to an array (returns an array).
stripos
Returns the numeric position of the first occurrence of needle in the haystack string.
stristr
Case-insensitive strstr(). Returns all of haystack from the first occurrence of needle to the end.
strstr
Find first occurrence of a string. Returns part of haystack string from the first occurrence of needle to the end of haystack.
strlen
Returns the length of the given string.
strtolower
Returns string with all alphabetic characters converted to lowercase.
strtoupper
Returns string with all alphabetic characters converted to uppercase.
substr
Return part of a string. Returns the portion of string specified by the start and length parameters.
substr_count(string $haystack, string $needle)
returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
substr_replace
replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
trim
Strip whitespace (or other characters) from the beginning and end of a string
strpos ($haystack, $needle)
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos() before PHP 5, this function can take a full string as the needle parameter and the entire string will be used.
strip_tags
Strip HTML and PHP tags from a string
str_replace
Replace all occurrences of the search string with the replacement string. If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().
ucfirst ($str)
Returns a string with the first character of $str capitalized (uppercase), if that character is alphabetic.
ucwords
Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

PHP regex functions

See this page for Perl-style PHP regex functions: http://www.php.net/manual/en/ref.pcre.php
See this page for POSIX-style PHP regex functions: http://www.php.net/manual/en/ref.regex.php

ereg
This function has been DEPRECATED as of PHP 5.3.0.
eregi
This function has been DEPRECATED as of PHP 5.3.0.
ereg_replace
This function has been DEPRECATED as of PHP 5.3.0.
eregi_replace
This function has been DEPRECATED as of PHP 5.3.0.
split
This function has been DEPRECATED as of PHP 5.3.0.
spliti
This function has been DEPRECATED as of PHP 5.3.0.
preg_filter
Identical to preg_replace() except it only returns the matches.
preg_grep (pattern, array)
Return array entries that match the pattern. Returns the array consisting of the elements of the input array that match the given pattern.
preg_match (pattern, subject[, submatches])
Perform a regular expression match. Searches subject for a match to the regular expression given in pattern.
preg_quote
Quote regular expression characters. Takes str and puts a backslash in front of every character that is part of the regular expression syntax.
preg_replace (pattern, replacement, subject)
Perform a regular expression search and replace.
preg_split
Split the given string by a regular expression.
trim
This function returns a string with whitespace stripped from the beginning and end of str.

PHP date and time functions

date
Returns a string formatted according to the given format string using the given integer timestamp.
date_add
An alias of DateTime::add, allows the addition of day(s),month(s),year(s) to the original date.
date_format
Returns date formatted according to given format.
mktime
Returns the Unix timestamp corresponding to the arguments given.
strtotime
Parse about any English textual datetime description into a Unix timestamp.
time
Returns the current time measured in the number of seconds since the Unix Epoch.

PHP variable functions

empty
Determine whether a variable is empty.
is_array
Finds whether a variable is an array.
is_int
Find whether the type of a variable is integer.
is_null
Finds whether the given variable is NULL.
is_numeric
Finds whether a variable is a number or a numeric string.
is_object
Finds whether the given variable is an object.
is_scalar
Finds whether a variable is a scalar.
isset
Determine if a variable is set and is not NULL.
unset
Unset a given variable.
print_r
Prints human-readable information about a variable.
var_dump
Dumps information about a variable. Displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

PHP HTML programming functions

base64_decode
Decodes data encoded with MIME base64.
base64_encode
Encodes the given data with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
get_headers
Fetches all the headers sent by the server in response to a HTTP request. returns an array with the headers sent by the server in response to a HTTP request.
htmlentities
Convert all applicable characters to HTML entities.
mail
Sends an email. (http://us2.php.net/manual/en/function.mail.php)
parse_url
Parses a URL and returns an associative array containing any of the various components of the URL that are present.
rawurldecode
Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters.
rawurlencode
Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits.
session_destroy
Destroys all data registered to a session.
session_get_cookie_params
Get the session cookie parameters (returns an array).
session_set_cookie_params
Set the session cookie parameters.
session_start
Creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
session_id
Get and/or set the current session id.
session_unset
Free all session variables.
setcookie
Defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
urldecode
Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.
urlencode
URL-encodes string.

http://www.php.net/manual/en/reserved.variables.php

$_ENV
An associative array of variables passed to the current script via the environment method.
$_GET
An associative array of variables passed to the current script via the URL parameters.
$_POST
An associative array of variables passed to the current script via the HTTP POST method.
$_COOKIE
An associative array of variables passed to the current script via HTTP Cookies.
$_SESSION
An associative array containing session variables available to the current script.
$_SERVER
An array containing information such as headers, paths, and script locations.
$_REQUEST
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$GLOBALS
An associative array containing references to all variables which are currently defined in the global scope of the script.

PHP number functions

http://us2.php.net/manual/en/ref.math.php

ceil
Returns the next highest integer value by rounding up value if necessary.
max
Finds the maximum value in an array, or in a series of parameters.
min
Finds the minimum value in an array, or in a series of parameters.
number_format
Format a number with grouped thousands.
rand
Generate a random number.
round
Rounds a float.

PHP files and filesystem functions

http://us2.php.net/manual/en/ref.filesystem.php

basename
Returns filename component of path.
copy
Makes a copy of the file source to dest.
delete
Use unlink() or unset().
fclose
Closes an open file pointer.
fgets
Gets line from file pointer.
file
Reads entire file into an array.
fopen
Opens file or URL.
fputs
Alias of fwrite().
fread
Binary-safe file read.
fwrite
Writes the contents of string to the file stream pointed to by handle.
is_dir
Tests whether the given filename is a directory.
is_file
Tests whether the given filename is a file.
parse_ini_file
Loads in the ini file (configuration file) specified in filename, and returns the settings in it in an associative array.
readfile
Reads a file and writes it to the output buffer.

PHP exec

exec
Execute an external program.
system
Execute an external program and display the output.

PHP network functions

fsockopen
Open Internet or Unix domain socket connection.
gethostbyaddr (string ip_address)
Get the Internet host name corresponding to a given IP address.
gethostbyname (string hostname)
Returns the IPv4 address of the Internet host specified by hostname.
gethostname
Gets the standard host name for the local machine.

PHP error reporting

Here's a link to the PHP error reporting page.

PHP PEAR Database Access with MDB2