PHP Functions Cheat Sheet

A List and Usage of Some of the Most Common PHP Function Reference Cheat Sheet

Home Short:

I oftentimes forget the syntax of some of the most commonly used PHP functions so I created this simple PHP functions cheat sheet which you can have open in your web browser for quick reference.

PHP String Functions

explode($separator, $string, [$number_of_array_parts]);

Break apart [$string] into an array of parts, splitting [$string] at each occurrence of [$separator].

  • [$number_of_array_parts] is a number that restricts the number of array parts produced via explode(). If [$number_of_array_parts] is a positive number, if for example your use of explode() would normally produce 10 array items and you specify 5 for [$number_of_array_parts], explode will stop breaking apart the string at the [$number_of_array_parts] and the last array element will contain the remaining string.
  • If [$number_of_array_parts] is a negative number then explode() will chop off ending array elements which will be minus what you specify for [$number_of_array_parts]. For example your use of explode() would normally produce 10 array items and you specify -5 for [$number_of_array_parts], explode will return the first 5 array elements, chopping of the last 5 elements.
  • see the companion function join() which is the opposite of explode() which takes an array and joins it together as a single string.
  • explode(' ','php programming makes me explode in my pants.') = Array([0]=>php [1]=>programming [2]=>makes [3]=>me [4]=>explode [5]=>in [6]=>my [7]=>pants.)
  • explode(' ','php programming makes me explode in my pants.', 3) = Array([0]=>php [1]=>programming [2]=>makes me explode in my pants.)
  • explode(' ','php programming makes me explode in my pants.', -3) = Array([0]=>php [1]=>programming [2]=>makes [3]=>me [4]=>explode)
implode([$join_character], $array);

Takes the parts of an [$array] and joins them into a string.

  • [$join_character] is the character to insert between each of the array parts to create the finished string. [$join_character] is optional and if omitted, an empty string "" is the default.
  • If [$join_character] is omitted, the correct syntax for implode is implode($array).
  • see the companion function explode() which is the opposite of implode() which takes a string and breaks it apart into an array.

In the examples below we will assume [$array] = Array([0]=>PHP [1]=>Programming [2]=>Makes me Explode in my Pants)

  • implode($array) = "PHPProgrammingMakes me Explode in my Pants"
  • implode(" ", $array) = "PHP Programming Makes me Explode in my Pants"
  • implode(" - ", $array) = "PHP - Programming - Makes me Explode in my Pants"
nl2br($string, [$xhtml_compatible]);

Function to insert proper HTML break tags to ensure a new line is output everwhere \n occurs in [$string]. The optional boolean [$xhtml_compatible] specified whether html line breaks are the more standard <br> or the XHTML compatible version of that which is <br/>.

  • The function parameter [$xhtml_compatible], in most cases does not need to be supplied and can be ignored.
  • nl2br('I love to\nprogram with php.\nIts fun!') =
    I love to
    program with php.
    It's fun!
str_contains($string, $strLookingFor); // case sensitive

Check to see if $string has or contains $strLookingFor.

  • Similar to php strpos() function.
  • str_contains() IS case sensitive. To do a case insensitive search use php function stripos().
  • str_contains("I love PHP programming", "PHP") = true
  • str_contains("I love PHP programming", "php") = false
str_pad($string, $output_length, [$padding_string], [$padding_type]);

Make a string a specific length so even if the actual string is shorter than [$output_length] [$string] gets padded so the final length is [$output_length]. Generally used for visual formatting purposes.

  • [$padding_string] is the character(s) to be used for the padding. The default is whitespace.
  • [$padding_type] where the padding is placed:
    • [1]STR_PAD_RIGHT (default - padding right side of [$string])
    • [2]STR_PAD_LEFT (padding left side of [$string])
    • [3]STR_PAD_BOTH (padding both sides of [$string]).
  • str_pad("php is fun", 20) = php is fun
  • str_pad("php is fun", 20, "#") = php is fun##########
  • str_pad("php is fun", 20, ":", STR_PAD_BOTH) = :::::php is fun:::::
str_replace($find, $replacement, $string, [$return_number_replacements]); // case sensitive

Find all instances of [$find] in [$string] and replace each of them with [$replacement]. [$return_number_replacements] is an optional variable that returns to you the number of replacements found.

  • Use strtolower() on $string and $find to make str_replace case ignored.
  • To perform multiple replacements use explode() on $find and $replacement.
  • str_replace("php", "javascript", "I love php code more than php for breakfast.") = I love javascript more than javascript for breakfast.
  • str_replace("php", "javascript", "I love PHP CODE more than php for breakfast.") = I love PHP CODE more than javascript for breakfast.
  • str_replace("php", "javascript", "I love php code more than php for breakfast.", $count) = I love javascript code more than javascript for breakfast. $count = 2
  • str_replace(explode("|", "lets|php|nap"), explode("|", "can we|javascript|break"), "lets do some php coding and then take a nap.") = can we do some javascript coding and then take a break.
str_split($string, [$each_arr_len]);

Split [$string] into an array, each element of the array being the length of [$each_arr_len].

  • If [each_arr_len] is ommited, the default length of 1 for each array element is the default.
  • If [each_arr_len] is larger than the length of [string] then the entire [string] will be returned as the only array element.
  • str_split("php is fun") = Array([0]=>p [1]=>h [2]=>p [3]=> [4]=>i [5]=>s [6]=> [7]=>f [8]=>u [9]=>n)
  • str_split("php programming is really fun", 5) = Array([0 =>php p [1]=>rogra [2]=>mming [3]=>is r [4]=>eally [5]=>fun)
  • str_split("php programming is really fun", 30) = Array([0] =>php programming is really fun)
strlen($string);

Returns the length number of characters of [$string].

  • strlen('I love to program with php!') = 27
strpos($string, $find, [$start]); // case sensitive

Returns position of first occurrence of [$find] within [$string].

  • If [find] not found returns false.
  • strpos('how are you feeling today?', 'you') = 8
stripos($string, $find, [$start]); // case ignored

Returns position of first occurrence of [$find] within [$string].

  • If [find] not found returns false.
  • stripos('how are you feeling today?', 'you') = 8
  • stripos('HOW ARE YOU FEELING TODAY?', 'you') = 8
strripos($string, $find, [$start]); // case ignored

Returns position of last occurrence of [$find] within [$string].

  • If [find] not found returns false.
  • strripos('how are you feeling today you php coder?', 'you') = 26
  • strripos('HOW ARE YOU FEELING TODAY YOU PHP CODER?', 'you') = 26
strstr($string, $find, [$return_before]); // case sensitive

Finds first occurrence of [$find] within [$string] and returns everything from the start of [$find] to the end.

  • If [return_before] set to true, the part of the string before [find] is returned.
  • If [find] not found returns false.
  • strstr('how are you feeling today?', 'you') = you feeling today?
  • strstr('how are you feeling today?', 'you', true) = how are
stristr($string, $find, [$return_before]); // case ignored

Finds first occurrence of [$find] within [$string] and returns everything from the start of [$find] to the end.

  • If [return_before] set to true, the part of the string before [find] is returned.
  • If [find] not found returns false;
  • stristr('how are you feeling today?', 'you') = you feeling today?
  • stristr('HOW ARE YOU FEELING TODAY?', 'you') = YOU FEELING TODAY?
  • stristr('how are you feeling today?', 'you', true) = how are
  • stristr('HOW ARE YOU FEELING TODAY?', 'you', true) = HOW ARE
strrev($string);

Takes [$string] and reverses the characters so the string read backwards.

  • strrev("Is my php programming backwards?") = ?sdrawkcab gnimmargorp php ym sI
strtolower($string);

Converts [$string] to all lowercase letters.

  • strtolower('Do you LOVE PHP coding?', 'you') = do you love php coding?
strtoupper($string);

Converts [$string] to all UPPER CASE letters.

  • strtoupper('do you love php?') = DO YOU LOVE PHP
ucfirst($string);

Converts first character of [$string] to upper case and leaves the rest of [$string] alone. To make an entire [$string] lower case with first letter capitalized use strtolower() to lowercase the entire [$string] first.

  • ucfirst('do you love php?') = Do you love php?
  • ucfirst('do you LOVE php?', 'you') = Do you LOVE php?
  • ucfirst(strtolower('do you LOVE PHP programming?')) = Do you love php programming?
ucwords($string);

Converts first letter of each word of [$string] to upper case. To capitialize just the first letter of the first word of [$string] use function [ucfirst].

  • ucwords('do you love web based programming?') = Do You Love Web Based Programming?
lcfirst($string);

Converts first character of [$string] to lower case and leaves the rest of [$string] alone.

  • lcfirst('Do you LOVE PHP programming?') = do you LOVE PHP programming?
substr($string, $startpos, [$length]);

Returns part of [$string] starting at [$startpos] and is the length of [$length].

  • If [length] is omitted, the entire string from [startpos] is returned.
  • A [startpos] of a negative number starts at that many characters backwards from the end of [string].
  • substr('how much do you love php?', 9) = do you love php?
  • substr('how much do you love php?', -9, 8) = love php
substr_count($string, $substring, [$start], [$length]); // case sensitive

Returns how many times [$substring] can be found within [$string] with [$start] being the start position to start searching for [$substring] within [$string] and [$length] being the endpoint of the search.

  • If [start] is a negative number then the substring search starts at that many character position backwards from the end of the string.
  • To make this function ignore case, make [string] and [substring] lower case first with strtolower().
  • substr_count("I am a PHP programmer and I love php programming", "php") = 1
  • substr_count("I am a PHP programmer and I love php programming", "php", -15) = 1
  • substr_count(strtolower("I am a PHP programmer and I love Php programming"),strtolower("php")) = 2; (ignoring case)
substr_replace($string, $replacement, $start, [$length]);

Replace [$string] or part of [$string] with [$replacement]. If [$start] = 0 and [$length] argument omitted, entire [$string] replaced with [$replacement].

  • substr_replace("How long have you been doing php code?", "I love php code", 0) =
    I love php code
  • substr_replace("How long have you been doing php code?", "I love php code", 23) =
    How long have you been I love php code
  • substr_replace("How long have you been doing php code?", "I love php code", 23, 22) =
    How long have you been I love php code

PHP Array Functions

array_fill($startIndex, $numberElements, $fillValues);

Create an array on the fly.

  • [$startIndex] is most typically 0 as this is the default of arrays in php but the $startIndex can be and number.
  • $createdArray = array_fill(0, 5, " -php is fun- "); = Array ( [0] => -php is fun- [1] => -php is fun- [2] => -php is fun- [3] => -php is fun- [4] => -php is fun- )
array_map($functionToMap, $arrToMap1, [$arrToMap2], ...);

Create an array by modifying the elements of an existing array $arrToMap1 via function $functionToMap.

  • $functionToMap can be an external function that is used but unless the $functionToMap is long or complicated, using an anonymous function directly within array_map $functionToMap is more concise and a better way to go.
  • Built in PHP function can be used for $functionToMap. Just surround the PHP function name within quotes ie "strtoupper".
  • $fruits = ["apple", "banana", "cherry"]; array_map("strtoupper", $fruits) = Array ([0] => APPLE [1] => BANANA [2] => CHERRY)
  • $names = ["Alice", "Bob", "Charlie"]; array_map(function($name){ return "User: " . $name; }, $names) = Array ( [0] => User: Alice [1] => User: Bob [2] => User: Charlie )
array_merge($array1, $array2, [$array3], [$array4] ...);

Combine/merge 2 or more arrays as a single new array.

  • If any array elements have the same key, the last one overrides the others.
  • $arr1 = ["dog", "cat", "bird"];
    $arr2 = ["red", "green", "yellow"];
    $arrMerged = array_merge($arr1, $arr2); = Array ( [0] => dog [1] => cat [2] => bird [3] => red [4] => green [5] => yellow )
array_shift($array);

Remove and return the first element of $array.

  • $arr = ["red", "green", "yellow"];
    $firstArrElem = array_shift($arr); # $firstArrElem = "red" and $arr = ["green", "yellow"]
array_unique($array, [$sortType]);

Removes any duplicates in array to ensure each element of $array is unique.

  • $sortType is optional and can be:
         SORT_STRING (default): compares items in $arr as strings
         SORT_REGULAR: compare items normally, doesn't change types
         SORT_NUMERIC: compares item numerically
         SORT_LOCALE_STRING: compare items as strings, based on current locale.
  • $arr = [99, 34, 12, 449, 12, 12]; array_unique($arr) = Array ( [0] => 99 [1] => 34 [2] => 12 [3] => 449 )
  • $arr = [99, "34", 12, 449, "12 ", 12]; array_unique($arr) = Array ( [0] => 99 [1] => 34 [2] => 12 [3] => 449 [4] => 12 )
  • $arr = [99, "34", 12, 449, "12 ", 12]; array_unique($arr, SORT_NUMERIC) = Array ( [0] => 99 [1] => 34 [2] => 12 [3] => 449 ) converts strings of numbers to numbers
array_unshift($array, $itemToAdd1, [$itemToAdd2, $itemToAdd3, ...]);

Insert new element(s) to the beginning of an array.

  • New elements $itemToAdd1, [$itemToAdd2, $itemToAdd3, ...] get inserted at the beginning of the array in the order supplied.
  • $arr = ["red", "green", "yellow"];
    array_unshift($arr, "yellow", "black") = ["yellow", "black", "red", "green", "yellow"]
in_array($searchFor, $arr, [$type]);

See if $searchFor can be found as an element in $arr. Returns TRUE if found or FALSE.

  • in_array() only seaches a flat or single level array and not a multidimensional array. To do this you would need to flatten the multidimensional array or perform a recursive search.
  • [$type] (true/false) if true, performs a strict search meaning if [$type] = false in_array() will return TRUE for both 1 and "1" if $arr contains either 1 or "1". If [$type] = true then the value as well as the type being searched for must match exactly.
  • $arr = [1, "2", 3]; in_array(2, $arr) = TRUE because [$type] by default is FALSE so 2 and "2" are the same.
  • $arr = [1, "2", 3]; in_array(2, $arr, true) = FALSE because [$type] = true so 2 is not the same variable type as "2".

PHP File Functions

file_exists($path_to_check);

Returns [true/false] whether file or path [$path_to_check] exists.

  • Results are cached. Use clearstatcach() to clear the cache.
  • file_exists($_SERVER['DOCUMENT_ROOT'] . "images/sample-img.png") // returns false if file/path doesn't exist or true if it does.
mkdir($path, $permissions, [$recursive], [$context]);

Creates a directory you specify via [$path]. Returns [true/false]. For [$path] you should use server path ie /var/www/html/project/newdirectory and not internet path https://website.com/project/newdirectory

[$permissions] is a 4 digit number which refers to read/write permissions of the newly created directory.

  • 1st # is always 0.
  • 2nd # indicates permissions for the owner.
  • 3rd # indicates permissions for the owners user group.
  • 4th # is permissions for anyone else.
Possible values for permissions are as follows: permissions number can be combined. For example to set read/write permission 2 + 4 = 6. To set execute/read/write 1 + 2 + 4 = 7.
  • 1 = execute permisions.
  • 2 = write permissions.
  • 4 = read permissions.
  • example #1: 0644 = read/write permissions for owner and read only for everyone else.
  • example #2: 0777 = read/write/execute permissions for all not recommended

If [$recursive] set to false, only the last directory item after the last / is created. If [$recursive] set to true, any parts of [$path] are created that don't exist.

move_uploaded_file($from, $to); // if file at [$to] already exists it will be overwritten

Takes a file uploaded via POST ie $file["tmp_name"] and places in the location specified by [$to].

  • The name of the file can be changed from the original $file["name"] by specifying the new name being part of the [$to] string, just be sure the appropriate file extension exits at the end of [$to].
  • For security its a good idea to not just move the uploaded file using $file["name"] but instead basename($file["name"])
  • move_uploaded_file($file["tmp_name"], $pathToWhereToSave . strtolower(basename($file["name"])));

Other Functions

error_log($err_message, [$err_dest_type], [$err_sent_to], [$email_headers]);

Saves php errors so they can be analyzed/debugged. These error messages can be sent to a log, file, or email address. The return is either true on success

$err_message = the text of the error message you want reported/printed.

[$err_dest_type] = where the error message will be saved or printed or output.

  • 0 = (default) file location of the error_log configuration set in the php.ini file.
  • 1 = sent to email address specified in [$err_sent_to].
  • 3 = save to a file location specified by [$err_sent_to].

[$err_sent_to] = where the error message will saved/sent/printed.

  • if [$err_dest_type] = 0 this parameter is not needed/used.
  • if [$err_dest_type] = 1 sent to email this would be an email address.
  • if [$err_dest_type] = 3 saved to file location this would be the local server file path ie $_SERVER["DOCUMENT_ROOT"] . "/files/err.log". use full, absolute and not relative paths ie "/files/err.log".

[$email_headers] is only used if [$err_dest_type] = 1 sent to email. Specifies email headers, like From, Cc, and Bcc. Multiple headers should be separated with a line break \r\n

  • error_log("Database failed to open") = Simplest usage of error_log() function. Prints the error message "Database failed to open" to error_log configuration set in the php.ini file
  • error_log("Database failed to open", 1, "[email protected]") = Emails the error message "Database failed to open" to [email protected].
  • error_log("Database failed to open") 3, $_SERVER["DOCUMENT_ROOT"] . "/files/err.log") = Appends the error message "Database failed to open" to the server file location $_SERVER["DOCUMENT_ROOT"] . "/files/err.log"
S
H
A
R
E