Tutorials › PHP Tutorial › PHP Function Reference

PHP Function Reference

10 min read · Lesson 23 of 24

This page is a quick reference for the built-in PHP functions used most often in this tutorial and in everyday projects. Each table links the function to what it does and a short example. For the complete list of thousands of functions, see the official manual at php.net.

Output and debugging

FunctionDescriptionExample
echooutputs one or more stringsecho "Hi", "!";
printoutputs one string, returns 1print "Hi";
printf()outputs a formatted stringprintf("%.2f", 3.456); gives 3.46
print_r()prints an array or object in readable formprint_r($arr);
var_dump()prints type and value, for debuggingvar_dump(5); gives int(5)
var_export()prints a value as valid PHP codevar_export([1, 2]);
exit() / die()stops the scriptexit("Done");

Strings

FunctionDescriptionExample
strlen()length in bytesstrlen("Kenya") gives 5
mb_strlen()length in characters (Unicode safe)mb_strlen("café") gives 4
strtoupper() / strtolower()change casestrtoupper("php") gives PHP
ucfirst() / ucwords()capitalise first letter / each worducwords("homa bay") gives Homa Bay
trim() / ltrim() / rtrim()remove surrounding whitespacetrim(" hi ") gives hi
str_contains()does the text contain a substring?str_contains("Nairobi", "rob") gives true
str_starts_with() / str_ends_with()check start / endstr_ends_with("a.php", ".php") gives true
strpos()position of first match, or falsestrpos("hello", "l") gives 2
substr()part of a stringsubstr("Kisumu", 0, 3) gives Kis
str_replace()replace all matchesstr_replace("a", "o", "mama") gives momo
str_pad()pad to a lengthstr_pad("5", 3, "0", STR_PAD_LEFT) gives 005
str_repeat()repeat a stringstr_repeat("-", 3) gives ---
strrev()reverse a stringstrrev("abc") gives cba
explode()split a string into an arrayexplode(",", "a,b") gives ["a", "b"]
implode()join an array into a stringimplode("-", [1, 2]) gives 1-2
sprintf()return a formatted stringsprintf("%03d", 7) gives 007
nl2br()turn newlines into <br> tagsnl2br("a\nb")
htmlspecialchars()escape text for safe HTML outputhtmlspecialchars("<b>") gives &lt;b&gt;
strip_tags()remove HTML tagsstrip_tags("<b>Hi</b>") gives Hi
preg_match()test a regular expressionpreg_match('/^\d+$/', "123") gives 1
preg_replace()replace using a regular expressionpreg_replace('/\s+/', " ", $text)

Numbers and math

FunctionDescriptionExample
round()round to the nearest valueround(2.567, 2) gives 2.57
floor() / ceil()round down / upceil(4.1) gives 5
abs()absolute valueabs(-8) gives 8
min() / max()smallest / largest valuemax(3, 9, 4) gives 9
sqrt() / pow()square root / powerpow(2, 8) gives 256
intdiv()integer divisionintdiv(17, 5) gives 3
random_int()secure random integerrandom_int(1, 6)
number_format()format with thousands separatorsnumber_format(1500.5, 2) gives 1,500.50
is_numeric()is it a number or numeric string?is_numeric("42") gives true
intval() / floatval()convert to int / floatintval("12abc") gives 12

Arrays

FunctionDescriptionExample
count()number of elementscount([1, 2, 3]) gives 3
array_sum()sum of valuesarray_sum([1, 2, 3]) gives 6
in_array()is a value in the array?in_array("b", ["a", "b"], true) gives true
array_search()key of a value, or falsearray_search("b", ["a", "b"]) gives 1
array_key_exists()does a key exist?array_key_exists("id", $row)
array_keys() / array_values()all keys / all valuesarray_keys(["a" => 1]) gives ["a"]
array_push() / array_pop()add to / remove from the endarray_pop($stack)
array_unshift() / array_shift()add to / remove from the startarray_shift($queue)
array_merge()join arraysarray_merge([1], [2]) gives [1, 2]
array_slice()extract part of an arrayarray_slice([1, 2, 3], 1) gives [2, 3]
array_unique()remove duplicatesarray_unique([1, 1, 2])
array_reverse()reverse orderarray_reverse([1, 2]) gives [2, 1]
array_map()apply a function to every valuearray_map(fn($x) => $x * 2, $a)
array_filter()keep values that pass a testarray_filter($a, fn($x) => $x > 0)
array_column()one column from a list of recordsarray_column($rows, "name")
range()build a sequencerange(1, 4) gives [1, 2, 3, 4]
sort() / rsort()sort values ascending / descendingsort($a);
asort() / arsort()sort by value, keep keysarsort($scores);
ksort() / krsort()sort by keyksort($prices);
usort()sort with your own compare functionusort($a, fn($x, $y) => $x <=> $y);

Variables and types

FunctionDescriptionExample
isset()variable exists and is not nullisset($_POST["email"])
empty()variable is missing or "falsy"empty("") gives true
unset()destroy a variable or array elementunset($arr[0]);
gettype() / get_debug_type()name of the typeget_debug_type(1.5) gives float
is_int(), is_string(), is_array(), is_bool(), is_null()type checksis_array([]) gives true
json_encode()convert a value to JSON textjson_encode(["a" => 1]) gives {"a":1}
json_decode()convert JSON text to a valuejson_decode('{"a":1}', true)

Date and time

FunctionDescriptionExample
date()format a timestampdate("Y-m-d")
time()current Unix timestamptime()
mktime()timestamp for a given datemktime(0, 0, 0, 12, 25, 2026)
strtotime()timestamp from English textstrtotime("+1 week")
date_default_timezone_set()set the default time zonedate_default_timezone_set("Africa/Nairobi")
checkdate()is a month/day/year valid?checkdate(2, 30, 2026) gives false

Forms, security and HTTP

FunctionDescriptionExample
filter_var()validate or sanitise a valuefilter_var($e, FILTER_VALIDATE_EMAIL)
filter_input()read and validate a request valuefilter_input(INPUT_GET, "id", FILTER_VALIDATE_INT)
password_hash()hash a password for storagepassword_hash($pw, PASSWORD_DEFAULT)
password_verify()check a password against a hashpassword_verify($pw, $hash)
bin2hex(random_bytes())secure random tokenbin2hex(random_bytes(16))
header()send an HTTP headerheader("Location: /login.php");
http_response_code()set the status codehttp_response_code(404);
session_start()start or resume a sessionsession_start();
session_regenerate_id()new session ID (use at login)session_regenerate_id(true);
session_destroy()end the sessionsession_destroy();
setcookie()send a cookiesetcookie("theme", "dark", ["expires" => time() + 86400]);

Files and includes

Statement / functionDescriptionExample
include / include_onceinsert a file; warning if missinginclude "header.php";
require / require_onceinsert a file; fatal error if missingrequire_once __DIR__ . "/db.php";
file_exists()does a file exist?file_exists("logo.png")
file_get_contents()read a whole file into a stringfile_get_contents("data.json")
file_put_contents()write a string to a filefile_put_contents("log.txt", $line, FILE_APPEND)
move_uploaded_file()save an uploaded filemove_uploaded_file($tmp, $dest)

PDO (database) methods

MethodDescription
new PDO($dsn, $user, $pass, $options)open a connection
$pdo->prepare($sql)prepare a statement with placeholders
$stmt->execute($values)run a prepared statement
$stmt->fetch()next row, or false
$stmt->fetchAll()all rows as an array
$stmt->fetchColumn()first column of the next row
$stmt->rowCount()rows affected by the last statement
$pdo->lastInsertId()ID of the last inserted row
$pdo->beginTransaction() / commit() / rollBack()transactions
Tip: Not sure what a function returns? Wrap it in var_dump() and run it. Seeing the exact type and value is often faster than reading the documentation.
Sign in or create a free account to track progress, earn XP, badges and a certificate.