PHP Built-in Functions (Step-by-Step Guide with Examples)

PHP comes with hundreds of built-in functions that simplify coding tasks. These functions handle strings, arrays, math, dates, file operations, and more.

1. What Are Built-in Functions in PHP?

Built-in functions are predefined PHP functions that perform specific tasks. You can call them directly without defining them.

Example: Using strlen() to Get String Length

<?php
$text = "Hello, PHP!";
echo strlen($text); // Output: 11
?>

➡ The strlen() function counts characters in a string.

2. PHP String Functions

PHP provides functions to manipulate strings.

Common String Functions

FunctionDescriptionExample
strlen()Returns the length of a stringstrlen("Hello") → 5
strtoupper()Converts a string to uppercasestrtoupper("php") → PHP
strtolower()Converts a string to lowercasestrtolower("PHP") → php
strpos()Finds the position of the first occurrence of a substringstrpos("Hello", "e") → 1
strrpos()Finds the position of the last occurrence of a substringstrrpos("Hello Hello", "e") → 7
str_replace()Replaces occurrences of a substring in a stringstr_replace("World", "PHP", "Hello World") → "Hello PHP"
substr()Extracts a part of a stringsubstr("Hello", 1, 3) → "ell"
strrev()Reverses a stringstrrev("Hello") → "olleH"
trim()Removes whitespace from both sides of a stringtrim(" Hello ") → "Hello"
ltrim()Removes whitespace from the left side of a stringltrim(" Hello") → "Hello"
rtrim()Removes whitespace from the right side of a stringrtrim("Hello ") → "Hello"
ucfirst()Capitalizes the first letter of a stringucfirst("hello") → "Hello"
lcfirst()Converts the first letter of a string to lowercaselcfirst("Hello") → "hello"
ucwords()Capitalizes the first letter of each worducwords("hello world") → "Hello World"
str_repeat()Repeats a string a specified number of timesstr_repeat("Hi ", 3) → "Hi Hi Hi "
str_shuffle()Randomly shuffles the characters in a stringstr_shuffle("hello") → "lohel" (Random output)
wordwrap()Wraps a string to a given number of characterswordwrap("This is a long sentence", 10, "\n")
htmlspecialchars()Converts special characters to HTML entitieshtmlspecialchars("<b>bold</b>") → "&lt;b&gt;bold&lt;/b&gt;"
html_entity_decode()Converts HTML entities back to charactershtml_entity_decode("&lt;b&gt;bold&lt;/b&gt;") → "<b>bold</b>"
addslashes()Adds backslashes before special charactersaddslashes("I'm PHP") → "I\'m PHP"
stripslashes()Removes backslashes added by addslashes()stripslashes("I\'m PHP") → "I'm PHP"
number_format()Formats a number with grouped thousandsnumber_format(10000.456, 2) → "10,000.46"

 

String Functions (addcslashes(), chr(), chop())

FunctionDescriptionExample
addcslashes()Escapes characters in a string with a backslash, based on a list of charactersaddcslashes("Hello", "e") → "H\e\llo"
chr()Returns a one-character string from a given ASCII valuechr(65) → "A"
chop()Alias for rtrim() — removes whitespace or other characters from the right side of a stringchop("Hello ") → "Hello"

Example: Replacing Text in a String

<?php
$text = "I love JavaScript!";
$newText = str_replace("JavaScript", "PHP", $text);
echo $newText; // Output: I love PHP!
?>

3. PHP Array Functions

PHP provides many built-in functions to manipulate arrays. Here’s a list of commonly used array functions:


FunctionDescriptionExample
count()Returns the number of elements in an arraycount([1, 2, 3]) → 3
sizeof()Alias of count()sizeof([1, 2, 3]) → 3
array_push()Adds one or more elements to the end of an array$arr = [1, 2]; array_push($arr, 3, 4);[1, 2, 3, 4]
array_pop()Removes and returns the last element of an array$arr = [1, 2, 3]; array_pop($arr);3
array_unshift()Adds elements to the beginning of an array$arr = [2, 3]; array_unshift($arr, 1);[1, 2, 3]
array_shift()Removes and returns the first element of an array$arr = [1, 2, 3]; array_shift($arr);1
array_merge()Merges two or more arraysarray_merge([1, 2], [3, 4]) → [1, 2, 3, 4]
array_combine()Creates an array using one array as keys and another as valuesarray_combine(["a", "b"], [1, 2]) → ["a" => 1, "b" => 2]
array_slice()Extracts a portion of an arrayarray_slice([1, 2, 3, 4], 1, 2)[2, 3]
array_splice()Removes elements and replaces them with new ones$arr = [1, 2, 3, 4]; array_splice($arr, 1, 2, ["X"]);[1, "X", 4]
array_keys()Returns an array of all keys from an arrayarray_keys(["a" => 1, "b" => 2]) → ["a", "b"]
array_values()Returns all values from an arrayarray_values(["a" => 1, "b" => 2]) → [1, 2]
array_flip()Swaps keys with values in an arrayarray_flip(["a" => 1, "b" => 2]) → [1 => "a", 2 => "b"]
array_reverse()Reverses the order of array elementsarray_reverse([1, 2, 3]) → [3, 2, 1]
array_unique()Removes duplicate values from an arrayarray_unique([1, 2, 2, 3]) → [1, 2, 3]
in_array()Checks if a value exists in an arrayin_array(2, [1, 2, 3]) → true
array_search()Searches for a value and returns its keyarray_search(2, [1, 2, 3]) → 1
array_diff()Returns the difference between arrays (values not in the second array)array_diff([1, 2, 3], [2, 3]) → [1]
array_intersect()Returns common values between arraysarray_intersect([1, 2, 3], [2, 3, 4]) → [2, 3]
array_map()Applies a function to each element of an arrayarray_map('strtoupper', ['a', 'b', 'c']) → ['A', 'B', 'C']
array_filter()Filters an array using a callback functionarray_filter([1, 2, 3, 4], fn($x) => $x % 2 == 0)[2, 4]
array_reduce()Reduces an array to a single value using a functionarray_reduce([1, 2, 3], fn($carry, $item) => $carry + $item, 0)6
sort()Sorts an array in ascending order$arr = [3, 1, 2]; sort($arr);[1, 2, 3]
rsort()Sorts an array in descending order$arr = [3, 1, 2]; rsort($arr);[3, 2, 1]
asort()Sorts an associative array by values$arr = ["b" => 2, "a" => 1]; asort($arr);["a" => 1, "b" => 2]
ksort()Sorts an associative array by keys$arr = ["b" => 2, "a" => 1]; ksort($arr);["a" => 1, "b" => 2]
shuffle()Randomizes the order of elements in an arrayshuffle($arr); → (Random output)

Example: Merging Arrays

<?php
$frontend = ["HTML", "CSS"];
$backend = ["PHP", "MySQL"];
$fullStack = array_merge($frontend, $backend);
print_r($fullStack);
?>

Output:

Array ( [0] => HTML [1] => CSS [2] => PHP [3] => MySQL )

4. PHP Math Functions

PHP has built-in functions for mathematical calculations.

Common Math Functions

FunctionDescriptionExample
abs()Absolute valueabs(-10)10
round()Rounds a numberround(4.7)5
ceil()Rounds upceil(4.3)5
floor()Rounds downfloor(4.7)4
sqrt()Square rootsqrt(16)4
rand()Random numberrand(1,100)

Example: Generating a Random Number

<?php
echo "Random number: " . rand(1, 100);
?>

5. PHP Date and Time Functions

PHP has built-in functions to handle date and time operations.

Common Date Functions

FunctionDescriptionExample
date()Formats a date/time stringdate("Y-m-d")"2025-02-12"
time()Returns current timestamptime()
strtotime()Converts string to timestampstrtotime("next Monday")

Example: Displaying the Current Date

<?php
echo "Today is: " . date("Y-m-d");
?>

6. PHP File Handling Functions

PHP provides functions to read, write, and modify files.

Common File Functions

FunctionDescriptionExample
fopen()Opens a filefopen("file.txt", "r")
fwrite()Writes to a filefwrite($file, "Hello!")
fread()Reads file contentfread($file, filesize("file.txt"))
fclose()Closes an open filefclose($file)

Example: Writing to a File

<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello, PHP!");
fclose($file);
?>

7. PHP Miscellaneous Functions

PHP also includes functions for error handling, debugging, and more.

Common Miscellaneous Functions

FunctionDescriptionExample
var_dump()Prints variable detailsvar_dump($array)
isset()Checks if variable is setisset($var)
empty()Checks if variable is emptyempty($var)
die()Stops script executiondie("Error!")
exit()Same as die()exit("Stopping!")

Example: Debugging with var_dump()

<?php
$data = ["PHP", "MySQL", "Laravel"];
var_dump($data);
?>

Output:

array(3) { [0]=> string(3) "PHP" [1]=> string(5) "MySQL" [2]=> string(7) "Laravel" }

var_dump() provides detailed output.

PHP Output Functions

PHP provides several functions for outputting data to the browser. These functions are used to display content like strings, variables, or structured data.


FunctionDescriptionExample
echo()Outputs one or more strings without returning a valueecho "Hello";
print()Outputs a string and returns 1, so it can be used in expressionsprint "Hello";
printf()Outputs a formatted stringprintf("My name is %s", "John");My name is John
sprintf()Returns a formatted string (similar to printf but doesn’t output it)$str = sprintf("My name is %s", "John"); echo $str;My name is John
print_r()Prints human-readable information about a variable (useful for arrays and objects)print_r([1, 2, 3]);[1, 2, 3]
var_dump()Dumps detailed information about a variable, including its type and valuevar_dump([1, 2, 3]);array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
var_export()Outputs or returns a valid PHP code representation of a variablevar_export([1, 2, 3]);array ( 0 => 1, 1 => 2, 2 => 3, )
ob_start()Starts output buffering (to send output to a buffer rather than to the browser)ob_start(); echo "Hello"; ob_end_flush();Hello
ob_get_contents()Gets the current buffer contents (used with output buffering)ob_start(); echo "Hello"; $output = ob_get_contents(); ob_end_clean();$output = "Hello"
FunctionDescriptionExample
bin2hex()Converts a binary string to its hexadecimal representationbin2hex("Hello") → "48656c6c6f"
chunk_split()Splits a string into smaller chunks of a specified lengthchunk_split("abcdef", 2) → "ab\ncd\nef\n"
convert_cyr_string()Converts a string from one Cyrillic character set to anotherconvert_cyr_string("Привет", "w", "k") → "Aopmf"
convert_uuencode()Encodes a string using uuencode encoding (used for encoding binary data for transmission)convert_uuencode("Hello") → "begin 644 /tmp/hello\n#0V%T\nend"
convert_uudecode()Decodes a string that was uuencoded using convert_uuencode()convert_uudecode("begin 644 /tmp/hello\n#0V%T\nend") → "Hello"
count_chars()Returns information about characters used in a stringcount_chars("hello", 3) → Array ( [104] => 1 [101] => 1 [108] => 2 [111] => 1 )
explode()Splits a string into an array based on a delimiterexplode(",", "apple,banana,orange") → ["apple", "banana", "orange"]
fprintf()Writes a formatted string to a file pointer (can be used to format data)fprintf($file, "Hello %s", "world") → "Hello world"
get_html_translation_table()Returns an associative array with HTML entities for characters or their reverseget_html_translation_table(HTML_ENTITIES) → Array ( ["<"] => "&lt;" ["&"] => "&amp;" )
hebrevc()Converts a string to Hebrew, and reverses the order of charactershebrevc("שלום") → "םולש"
hex2bin()Converts a hexadecimal string to its binary representationhex2bin("48656c6c6f") → "Hello"