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
Function | Description | Example |
---|---|---|
strlen() | Returns the length of a string | strlen("Hello") → 5 |
strtoupper() | Converts a string to uppercase | strtoupper("php") → PHP |
strtolower() | Converts a string to lowercase | strtolower("PHP") → php |
strpos() | Finds the position of the first occurrence of a substring | strpos("Hello", "e") → 1 |
strrpos() | Finds the position of the last occurrence of a substring | strrpos("Hello Hello", "e") → 7 |
str_replace() | Replaces occurrences of a substring in a string | str_replace("World", "PHP", "Hello World") → "Hello PHP" |
substr() | Extracts a part of a string | substr("Hello", 1, 3) → "ell" |
strrev() | Reverses a string | strrev("Hello") → "olleH" |
trim() | Removes whitespace from both sides of a string | trim(" Hello ") → "Hello" |
ltrim() | Removes whitespace from the left side of a string | ltrim(" Hello") → "Hello" |
rtrim() | Removes whitespace from the right side of a string | rtrim("Hello ") → "Hello" |
ucfirst() | Capitalizes the first letter of a string | ucfirst("hello") → "Hello" |
lcfirst() | Converts the first letter of a string to lowercase | lcfirst("Hello") → "hello" |
ucwords() | Capitalizes the first letter of each word | ucwords("hello world") → "Hello World" |
str_repeat() | Repeats a string a specified number of times | str_repeat("Hi ", 3) → "Hi Hi Hi " |
str_shuffle() | Randomly shuffles the characters in a string | str_shuffle("hello") → "lohel" (Random output) |
wordwrap() | Wraps a string to a given number of characters | wordwrap("This is a long sentence", 10, "\n") |
htmlspecialchars() | Converts special characters to HTML entities | htmlspecialchars("<b>bold</b>") → "<b>bold</b>" |
html_entity_decode() | Converts HTML entities back to characters | html_entity_decode("<b>bold</b>") → "<b>bold</b>" |
addslashes() | Adds backslashes before special characters | addslashes("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 thousands | number_format(10000.456, 2) → "10,000.46" |
String Functions (addcslashes(), chr(), chop())
Function | Description | Example |
---|---|---|
addcslashes() | Escapes characters in a string with a backslash, based on a list of characters | addcslashes("Hello", "e") → "H\e\llo" |
chr() | Returns a one-character string from a given ASCII value | chr(65) → "A" |
chop() | Alias for rtrim() — removes whitespace or other characters from the right side of a string | chop("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:
Function | Description | Example |
---|---|---|
count() | Returns the number of elements in an array | count([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 arrays | array_merge([1, 2], [3, 4]) → [1, 2, 3, 4] |
array_combine() | Creates an array using one array as keys and another as values | array_combine(["a", "b"], [1, 2]) → ["a" => 1, "b" => 2] |
array_slice() | Extracts a portion of an array | array_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 array | array_keys(["a" => 1, "b" => 2]) → ["a", "b"] |
array_values() | Returns all values from an array | array_values(["a" => 1, "b" => 2]) → [1, 2] |
array_flip() | Swaps keys with values in an array | array_flip(["a" => 1, "b" => 2]) → [1 => "a", 2 => "b"] |
array_reverse() | Reverses the order of array elements | array_reverse([1, 2, 3]) → [3, 2, 1] |
array_unique() | Removes duplicate values from an array | array_unique([1, 2, 2, 3]) → [1, 2, 3] |
in_array() | Checks if a value exists in an array | in_array(2, [1, 2, 3]) → true |
array_search() | Searches for a value and returns its key | array_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 arrays | array_intersect([1, 2, 3], [2, 3, 4]) → [2, 3] |
array_map() | Applies a function to each element of an array | array_map('strtoupper', ['a', 'b', 'c']) → ['A', 'B', 'C'] |
array_filter() | Filters an array using a callback function | array_filter([1, 2, 3, 4], fn($x) => $x % 2 == 0) → [2, 4] |
array_reduce() | Reduces an array to a single value using a function | array_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 array | shuffle($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
Function | Description | Example |
---|---|---|
abs() | Absolute value | abs(-10) → 10 |
round() | Rounds a number | round(4.7) → 5 |
ceil() | Rounds up | ceil(4.3) → 5 |
floor() | Rounds down | floor(4.7) → 4 |
sqrt() | Square root | sqrt(16) → 4 |
rand() | Random number | rand(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
Function | Description | Example |
---|---|---|
date() | Formats a date/time string | date("Y-m-d") → "2025-02-12" |
time() | Returns current timestamp | time() |
strtotime() | Converts string to timestamp | strtotime("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
Function | Description | Example |
---|---|---|
fopen() | Opens a file | fopen("file.txt", "r") |
fwrite() | Writes to a file | fwrite($file, "Hello!") |
fread() | Reads file content | fread($file, filesize("file.txt")) |
fclose() | Closes an open file | fclose($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
Function | Description | Example |
---|---|---|
var_dump() | Prints variable details | var_dump($array) |
isset() | Checks if variable is set | isset($var) |
empty() | Checks if variable is empty | empty($var) |
die() | Stops script execution | die("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.
Function | Description | Example |
---|---|---|
echo() | Outputs one or more strings without returning a value | echo "Hello"; |
print() | Outputs a string and returns 1, so it can be used in expressions | print "Hello"; |
printf() | Outputs a formatted string | printf("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 value | var_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 variable | var_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" |
Function | Description | Example |
---|---|---|
bin2hex() | Converts a binary string to its hexadecimal representation | bin2hex("Hello") → "48656c6c6f" |
chunk_split() | Splits a string into smaller chunks of a specified length | chunk_split("abcdef", 2) → "ab\ncd\nef\n" |
convert_cyr_string() | Converts a string from one Cyrillic character set to another | convert_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 string | count_chars("hello", 3) → Array ( [104] => 1 [101] => 1 [108] => 2 [111] => 1 ) |
explode() | Splits a string into an array based on a delimiter | explode(",", "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 reverse | get_html_translation_table(HTML_ENTITIES) → Array ( ["<"] => "<" ["&"] => "&" ) |
hebrevc() | Converts a string to Hebrew, and reverses the order of characters | hebrevc("שלום") → "םולש" |
hex2bin() | Converts a hexadecimal string to its binary representation | hex2bin("48656c6c6f") → "Hello" |