Table of contents
- Library/Built-in Function in PHP
- 1.Here's a list of commonly used array functions in PHP:
- 2.Here's a list of commonly used string functions in PHP:
- 3.Here's a list of commonly used file system functions in PHP:
- 4.Database functions in PHP
- 5.Here are some commonly used functions for database operations using PDO (PHP Data Objects):
- 6.Here are some commonly used date and time functions in PHP:
- 7.Here are some commonly used mathematical functions in PHP:
- 8.Regular expression functions
- 9.Network-related functions
- 10.Miscellaneous Functions
Library/Built-in Function in PHP
Here's an overview of the main functionality for each category of functions in PHP:
1.Array Functions:
Creation and Modification:
array()
- Create an arrayarray_push()
- Push one or more elements onto the end of an arrayarray_pop()
- Pop the element off the end of an arrayarray_merge()
- Merge one or more arraysarray_filter()
- Filters elements of an array using a callback functionarray_map()
- Applies a callback function to each element of an array
Access and Search:
count()
- Count the number of elements in an arrayin_array()
- Checks if a value exists in an arrayarray_key_exists()
- Checks if a specific key exists in an arrayarray_search()
- Searches for a value in an array and returns the corresponding key
Iteration:
foreach()
- Loop through each key/value pair in an arrayarray_walk()
- Apply a user-defined function to each element of an array
2.String Functions:
Manipulation:
strlen()
- Get the length of a stringstrpos()
- Find the position of the first occurrence of a substring in a stringstr_replace()
- Replace all occurrences of the search string with the replacement stringsubstr()
- Return part of a stringtrim()
- Strip whitespace (or other characters) from the beginning and end of a string
Case and Formatting:
strtolower()
- Convert a string to lowercasestrtoupper()
- Convert a string to uppercaseucwords()
- Uppercase the first character of each word in a string
3.File System Functions:
File Handling:
file_get_contents()
- Reads the entire content of a file into a stringfile_put_contents()
- Write a string to a filefopen()
- Opens a file or URLfclose()
- Closes an open file pointer
Directory Handling:
mkdir()
- Makes a directoryrmdir()
- Removes a directoryscandir()
- List files and directories inside a specified path
4.Database Functions:
MySQLi Functions:
mysqli_connect()
- Open a new connection to the MySQL servermysqli_query()
- Performs a query on the databasemysqli_fetch_assoc()
- Fetch a result row as an associative array
5.Database Functions (for PDO):
PDO Functions:
PDO::__construct()
- Creates a new PDO instancePDO::prepare()
- Prepares a statement for execution and returns a statement objectPDOStatement::execute()
- Executes a prepared statement
6.Date and Time Functions:
date()
- Format a local time/datetime()
- Return the current Unix timestampstrtotime()
- Parse about any English textual datetime description into a Unix timestampdate_diff()
- Returns the difference between two DateTime objects
7.Mathematical Functions:
abs()
- Absolute valuesqrt()
- Square rootpow()
- Exponential expressionrand()
- Generate a random integermin()
andmax()
- Find the lowest and highest values in an array
8.Regular Expression Functions:
preg_match()
- Perform a regular expression matchpreg_replace()
- Perform a regular expression search and replacepreg_split()
- Split string by a regular expression
9.Network Functions:
fsockopen()
- Open Internet or Unix domain socket connectionfile_get_contents()
- Reads entire file into a stringcurl_init()
- Initialize a cURL session
10.Miscellaneous Functions:
isset()
- Determine if a variable is set and is not NULLempty()
- Determine whether a variable is emptydie()
- Equivalent to exitecho()
- Output one or more stringsvar_dump()
- Dumps information about a variable
Please note that this is just an overview, and there are many more functions and options available for each category. For detailed information and usage examples, refer to the official PHP documentation at php.net
1.Here's a list of commonly used array functions in PHP:
count()
: Returns the number of elements in an array.$arr = [1, 2, 3, 4, 5]; $count = count($arr);
array_push()
: Adds one or more elements to the end of an array.$arr = [1, 2, 3]; array_push($arr, 4, 5);
array_pop()
: Removes and returns the last element of an array.$arr = [1, 2, 3, 4, 5]; $lastElement = array_pop($arr);
array_merge()
: Combines two or more arrays into one array.$arr1 = [1, 2, 3]; $arr2 = [4, 5, 6]; $mergedArray = array_merge($arr1, $arr2);
array_filter()
: Filters elements of an array using a callback function.$arr = [1, 2, 3, 4, 5]; $filteredArray = array_filter($arr, function($value) { return $value > 2; });
array_map()
: Applies a callback function to each element of an array.$arr = [1, 2, 3, 4, 5]; $squaredArray = array_map(function($value) { return $value * $value; }, $arr);
array_key_exists()
: Checks if the given key or index exists in the array.$arr = ['name' => 'John', 'age' => 30]; if (array_key_exists('name', $arr)) { // Key 'name' exists in the array }
array_search()
: Searches the array for a given value and returns the corresponding key if successful.$arr = ['apple', 'orange', 'banana']; $key = array_search('orange', $arr);
array_reverse()
: Returns an array with elements in the reverse order.$arr = [1, 2, 3, 4, 5]; $reversedArray = array_reverse($arr);
array_unique()
: Removes duplicate values from an array.$arr = [1, 2, 2, 3, 4, 4, 5]; $uniqueArray = array_unique($arr);
These are just a few examples, and there are many more array functions available in PHP. You can refer to the official PHP documentation for a comprehensive list and detailed explanations of each function: PHP Array Functions.
2.Here's a list of commonly used string functions in PHP:
strlen()
: Returns the length of a string.$str = "Hello, World!"; $length = strlen($str);
strpos()
: Finds the position of the first occurrence of a substring in a string.$str = "Hello, World!"; $position = strpos($str, "World");
str_replace()
: Replaces all occurrences of a search string with a replacement string.$str = "Hello, World!"; $newStr = str_replace("World", "John", $str);
strtolower()
: Converts a string to lowercase.$str = "Hello, World!"; $lowercaseStr = strtolower($str);
strtoupper()
: Converts a string to uppercase.$str = "Hello, World!"; $uppercaseStr = strtoupper($str);
substr()
: Returns a part of a string.$str = "Hello, World!"; $substring = substr($str, 0, 5); // Returns "Hello"
trim()
: Removes whitespace or other characters from the beginning and end of a string.$str = " Hello, World! "; $trimmedStr = trim($str);
explode()
: Splits a string by a specified delimiter and returns an array.$str = "apple,orange,banana"; $fruits = explode(",", $str);
implode()
(orjoin()
): Joins array elements with a string.$fruits = ["apple", "orange", "banana"]; $str = implode(", ", $fruits);
strrev()
: Reverses a string.$str = "Hello, World!"; $reversedStr = strrev($str);
str_pad()
: Pads a string to a certain length with another string.$str = "Hello"; $paddedStr = str_pad($str, 10, "*");
strcmp()
: Compares two strings.$str1 = "Hello"; $str2 = "hello"; $result = strcmp($str1, $str2);
These are just a few examples, and there are many more string functions available in PHP. You can refer to the official PHP documentation for a comprehensive list and detailed explanations of each function: PHP String Functions.
3.Here's a list of commonly used file system functions in PHP:
file_get_contents()
: Reads the entire content of a file into a string.$content = file_get_contents("example.txt");
file_put_contents()
: Writes a string to a file.$data = "Hello, World!"; file_put_contents("example.txt", $data);
fopen()
,fwrite()
,fclose()
: Functions for opening, writing to, and closing files.$file = fopen("example.txt", "w"); fwrite($file, "Hello, World!"); fclose($file);
unlink()
: Deletes a file.unlink("example.txt");
file_exists()
: Checks if a file or directory exists.$exists = file_exists("example.txt");
is_file()
: Checks if the given file is a regular file.$isFile = is_file("example.txt");
is_dir()
: Checks if the given path is a directory.$isDir = is_dir("example_directory");
mkdir()
: Creates a directory.mkdir("new_directory");
rmdir()
: Removes a directory.rmdir("empty_directory");
copy()
: Copies a file.copy("source.txt", "destination.txt");
rename()
: Renames a file or directory.rename("old_name.txt", "new_name.txt");
file()
: Reads an entire file into an array.$lines = file("example.txt");
glob()
: Returns an array of filenames that match a specified pattern.$files = glob("*.txt");
filesize()
: Gets the size of a file.$size = filesize("example.txt");
filemtime()
: Gets the last modified time of a file.$lastModified = filemtime("example.txt");
These are just a few examples, and there are many more file system functions available in PHP. You can refer to the official PHP documentation for a comprehensive list and detailed explanations of each function: PHP Filesystem Functions.
4.Database functions in PHP
Database functions in PHP can vary depending on the database system you are using. Below are examples of commonly used functions for MySQL databases, using MySQLi:
mysqli_connect()
: Opens a new connection to the MySQL server.$conn = mysqli_connect("hostname", "username", "password", "database");
mysqli_query()
: Performs a query on the database.$query = "SELECT * FROM users"; $result = mysqli_query($conn, $query);
mysqli_fetch_assoc()
: Fetches a result row as an associative array.while ($row = mysqli_fetch_assoc($result)) { // Process each row }
mysqli_num_rows()
: Gets the number of rows in a result.$numRows = mysqli_num_rows($result);
mysqli_insert_id()
: Returns the auto-generated id used in the last query.$lastId = mysqli_insert_id($conn);
mysqli_error()
: Returns a string description of the last error.if (!$result) { echo "Error: " . mysqli_error($conn); }
mysqli_real_escape_string()
: Escapes special characters in a string for use in an SQL statement.$input = "It's a sample input"; $escapedInput = mysqli_real_escape_string($conn, $input);
mysqli_close()
: Closes the previously opened database connection.mysqli_close($conn);
5.Here are some commonly used functions for database operations using PDO (PHP Data Objects):
PDO::__construct()
: Creates a new PDO instance representing a connection to a database.$dsn = "mysql:host=hostname;dbname=database"; $user = "username"; $password = "password"; $pdo = new PDO($dsn, $user, $password);
PDO::prepare()
: Prepares a statement for execution and returns a statement object.$query = "SELECT * FROM users WHERE id = :id"; $stmt = $pdo->prepare($query);
PDOStatement::bindParam()
: Binds a parameter to the specified variable name.$id = 1; $stmt->bindParam(':id', $id, PDO::PARAM_INT);
PDOStatement::execute()
: Executes a prepared statement.$stmt->execute();
PDOStatement::fetch()
: Fetches the next row from a result set.$row = $stmt->fetch(PDO::FETCH_ASSOC);
PDOStatement::fetchAll()
: Returns an array containing all of the result set rows.$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
PDO::query()
: Executes an SQL statement, returning a result set as a PDOStatement object.$result = $pdo->query("SELECT * FROM users");
PDO::exec()
: Executes an SQL statement and returns the number of affected rows.$rowCount = $pdo->exec("DELETE FROM users WHERE id = 1");
PDOStatement::rowCount()
: Returns the number of rows affected by the last SQL statement.$rowCount = $stmt->rowCount();
PDO::lastInsertId()
: Returns the ID of the last inserted row or sequence value.$lastId = $pdo->lastInsertId();
PDO::beginTransaction()
,PDO::commit()
,PDO::rollBack()
: Methods for handling transactions.try { $pdo->beginTransaction(); // Perform database operations $pdo->commit(); } catch (PDOException $e) { $pdo->rollBack(); echo "Failed: " . $e->getMessage(); }
PDO::setAttribute()
: Sets an attribute on the database handle.$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
These functions provide a foundation for interacting with databases using PDO in PHP. Remember to handle database connections and queries securely to prevent SQL injection and other security issues. Always use prepared statements or parameterized queries to enhance security.
6.Here are some commonly used date and time functions in PHP:
date()
: Formats a local time/date.echo date("Y-m-d H:i:s"); // Current date and time
time()
: Returns the current Unix timestamp.$timestamp = time();
strtotime()
: Parses any English textual datetime description into a Unix timestamp.$timestamp = strtotime("next Sunday");
mktime()
: Returns the Unix timestamp for a date.$timestamp = mktime(12, 0, 0, 3, 15, 2023); // March 15, 2023, 12:00 PM
date_create()
anddate_format()
: Object-oriented way to work with dates.$date = date_create('2023-11-20'); echo date_format($date, 'Y-m-d');
date_diff()
: Calculates the difference between two DateTime objects.$date1 = date_create('2023-11-20'); $date2 = date_create('2023-12-25'); $interval = date_diff($date1, $date2); echo $interval->format('%R%a days');
strftime()
andgmstrftime()
: Formats a local or GMT/UTC time and/or date according to locale settings.setlocale(LC_TIME, 'en_US'); echo strftime("%A, %B %d, %Y %H:%M:%S"); // Monday, November 20, 2023 15:30:00
date_default_timezone_set()
: Sets the default timezone used by all date/time functions.date_default_timezone_set('America/New_York');
getdate()
: Returns an associative array containing information about the date.$dateInfo = getdate(); print_r($dateInfo);
checkdate()
: Validates a Gregorian date.$isValid = checkdate(2, 29, 2020); // Check if February 29, 2020, is a valid date
strtotime()
withdate()
: Convert a timestamp to a formatted date.$timestamp = strtotime('2023-11-20'); $formattedDate = date('Y-m-d', $timestamp);
microtime()
: Returns the current Unix timestamp with microseconds.$microtime = microtime(true);
These functions allow you to manipulate and format date and time values in various ways. Keep in mind that the actual output may vary based on the server's time zone and locale settings.
7.Here are some commonly used mathematical functions in PHP:
abs()
: Returns the absolute value of a number.$absoluteValue = abs(-5); // Result: 5
ceil()
: Rounds a number up to the nearest integer.$roundedUp = ceil(4.3); // Result: 5
floor()
: Rounds a number down to the nearest integer.$roundedDown = floor(4.8); // Result: 4
round()
: Rounds a float to the nearest integer.$rounded = round(4.5); // Result: 5
max()
: Returns the highest value from a list of arguments.$maximum = max(2, 7, 1, 9); // Result: 9
min()
: Returns the lowest value from a list of arguments.$minimum = min(2, 7, 1, 9); // Result: 1
pow()
or**
: Raises a number to the power of another.$power = pow(2, 3); // Result: 8
sqrt()
: Returns the square root of a number.$squareRoot = sqrt(9); // Result: 3
rand()
: Generates a random integer.$randomNumber = rand(1, 100); // Generates a random number between 1 and 100
mt_rand()
: Generates a random integer using the Mersenne Twister algorithm.$randomNumber = mt_rand(1, 100); // Generates a random number between 1 and 100
log()
: Returns the natural logarithm of a number.$logValue = log(10); // Result: 2.302585092994
exp()
: Returns e raised to the power of a number.$exponential = exp(2); // Result: 7.3890560989307
sin()
,cos()
,tan()
: Trigonometric functions (sine, cosine, tangent).$sinValue = sin(deg2rad(30)); // Sine of 30 degrees
deg2rad()
,rad2deg()
: Converts degrees to radians and radians to degrees.$radians = deg2rad(45); // Converts 45 degrees to radians
These are some of the basic mathematical functions in PHP. There are more advanced mathematical functions available, and you can refer to the official PHP documentation for a comprehensive list: PHP Mathematical Functions.
8.Regular expression functions
In PHP, regular expression functions are part of the PCRE (Perl Compatible Regular Expressions) extension. Here are some commonly used regular expression functions:
preg_match()
: Performs a regular expression match.$pattern = '/[0-9]+/'; $subject = 'There are 123 apples.'; preg_match($pattern, $subject, $matches);
preg_match_all()
: Performs a global regular expression match.$pattern = '/[0-9]+/'; $subject = 'There are 123 apples and 456 oranges.'; preg_match_all($pattern, $subject, $matches);
preg_replace()
: Performs a regular expression search and replace.$pattern = '/apple/'; $replacement = 'banana'; $subject = 'I have an apple.'; $result = preg_replace($pattern, $replacement, $subject);
preg_split()
: Splits a string by a regular expression.$pattern = '/\s+/'; $subject = 'This is a sentence.'; $words = preg_split($pattern, $subject);
preg_quote()
: Quote regular expression characters.$input = 'a*b'; $pattern = '/^' . preg_quote($input, '/') . '$/';
preg_grep()
: Return array entries that match the pattern.$pattern = '/[0-9]+/'; $array = ['apple', '123', 'orange']; $result = preg_grep($pattern, $array);
preg_filter()
: Perform a regular expression search and replace using callbacks.$pattern = '/[0-9]+/'; $subject = ['apple', '123', 'orange']; $result = preg_filter($pattern, 'X', $subject);
preg_match_callback()
: Perform a regular expression match and call a callback function.$pattern = '/[0-9]+/'; $subject = 'There are 123 apples.'; preg_match_callback($pattern, function ($matches) { // Callback function print_r($matches); }, $subject);
These functions are used for pattern matching and manipulation with regular expressions in PHP. Regular expressions provide a powerful way to search, match, and manipulate strings based on specific patterns. The patterns are defined using a special syntax, and you can refer to the official PHP documentation for more details: PHP PCRE Functions.
9.Network-related functions
PHP provides various network-related functions for working with URLs, sockets, and other networking tasks. Here are some commonly used network functions:
file_get_contents()
: Reads the entire content of a file or URL into a string.$content = file_get_contents('https://example.com');
fopen()
,fread()
,fclose()
: Functions for opening, reading from, and closing files, including URLs.$file = fopen('https://example.com', 'r'); $content = fread($file, 1024); fclose($file);
fsockopen()
: Opens a network connection or a socket.$socket = fsockopen('example.com', 80, $errno, $errstr, 30);
gethostbyname()
: Returns the IPv4 address of a given Internet host name.$ip = gethostbyname('example.com');
gethostbyaddr()
: Returns the host name of the Internet host specified by the IP address.$hostname = gethostbyaddr('93.184.216.34');
parse_url()
: Parses a URL and returns its components.$url = 'https://example.com/path/to/page?query=string'; $components = parse_url($url);
urlencode()
andurldecode()
: URL-encode and URL-decode a string.$encodedString = urlencode('Hello World!'); $decodedString = urldecode($encodedString);
http_build_query()
: Generates URL-encoded query string.$params = ['name' => 'John', 'age' => 30]; $queryString = http_build_query($params);
curl_init()
,curl_setopt()
,curl_exec()
,curl_close()
: Functions for using cURL to make HTTP requests.$ch = curl_init('https://example.com/api'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
get_headers()
: Fetches all the headers sent by the server in response to an HTTP request.$headers = get_headers('https://example.com');
ip2long()
andlong2ip()
: Converts an IP address to a long integer and vice versa.$ipLong = ip2long('192.168.0.1'); $ipString = long2ip($ipLong);
filter_var()
andfilter_var_array()
: Filters a variable with a specified filter.$email = 'user@example.com'; $filteredEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
These functions are commonly used for network-related tasks in PHP, including working with URLs, sockets, and making HTTP requests. The choice of function depends on the specific task you need to accomplish. Always handle user input and network data securely to prevent security vulnerabilities.
10.Miscellaneous Functions
"Miscellaneous Functions" can encompass a wide range of functions that don't fit neatly into specific categories. Here are some miscellaneous functions in PHP:
isset()
: Determine if a variable is set and is not null.$variable = 'some value'; if (isset($variable)) { // Variable is set }
empty()
: Determine if a variable is empty.$value = ''; if (empty($value)) { // Variable is empty }
unset()
: Unset a variable.$variable = 'some value'; unset($variable);
defined()
: Checks whether a given constant exists.define('MY_CONSTANT', 'some value'); if (defined('MY_CONSTANT')) { // Constant is defined }
die()
andexit()
: Output a message and terminate the current script.if ($errorCondition) { die('Error: Script terminated.'); }
sleep()
: Delays the execution of the script for a specified number of seconds.sleep(5); // Sleep for 5 seconds
usleep()
: Delays the execution of the script in microseconds.usleep(500000); // Sleep for 0.5 seconds
header()
: Send a raw HTTP header.header('Location: https://example.com');
error_reporting()
: Set the error reporting level at runtime.error_reporting(E_ALL); // Report all errors
ini_set()
: Sets the value of a configuration option.ini_set('display_errors', 1); // Display errors
gettype()
: Get the type of a variable.$variable = 42; $type = gettype($variable); // Returns 'integer'
is_callable()
: Verify that the contents of a variable can be called as a function.$callable = 'myFunction'; if (is_callable($callable)) { $callable(); // Call the function }
get_defined_vars()
: Returns an associative array with the names of all variables and their values.$var1 = 'value1'; $var2 = 'value2'; $allVariables = get_defined_vars();
memory_get_usage()
andmemory_get_peak_usage()
: Get the current and peak memory usage.$currentMemoryUsage = memory_get_usage(); $peakMemoryUsage = memory_get_peak_usage();
microtime()
: Returns the current Unix timestamp with microseconds.$microtime = microtime(true);
These are just a few examples of miscellaneous functions in PHP. They cover a range of tasks, including variable handling, script termination, sleep/delay, header manipulation, and more. The use of these functions depends on the specific requirements of your application. Always refer to the PHP documentation for the most up-to-date information and additional functions: PHP Manual.