Table of Contents
In this article, we’ll learn about Functions in PHP, explore their various types, discuss their significance, and provide practical examples to illustrate their usage.
What are PHP Functions?
A function in PHP is a block of code that performs a specific task or set of tasks. It is designed to be reusable, which means you can call it multiple times from different parts of your code without having to rewrite the same logic each time. Functions encapsulate functionality, making it easier to manage and understand complex codebases.
Function Syntax
Defining a function in PHP follows a straightforward syntax:
function functionName(parameters) {
// Function body (code block)
// Optional return statement
}
functionName
: This is the name of the function, which should be unique within the PHP script.parameters
: These are optional input values that the function can accept. You can define multiple parameters separated by commas.- Function Body: This is the block of code that executes when the function is called.
- Return Statement: The optional return statement allows the function to send a value back to the caller. If not specified, the function implicitly returns
null
.
Types of PHP Functions
- Built-in Functions: PHP comes with an extensive set of built-in functions that cover a wide range of functionalities, including string manipulation, array operations, mathematical calculations, date handling, and more. These functions are readily available for use in any PHP script without the need for additional libraries or installations.
- User-defined Functions: Developers can create their own custom functions tailored to specific application requirements. User-defined functions enhance code modularity and facilitate better code management.
PHP Function Examples
Let’s explore some practical examples of both built-in and user-defined functions to illustrate their usage.
Example 1 : Built-in Function – strlen()
The strlen()
function is used to determine the length of a given string.
<?php
$sampleString = "Hello, world!";
$length = strlen($sampleString);
echo "The length of the string is: $length"; // Output: The length of the string is: 13
?>
Example 2: Built-in Function – array_sum()
The array_sum()
function calculates the sum of all values in an array.
<?php
$numbers = [2, 4, 6, 8, 10];
$sum = array_sum($numbers);
echo "The sum of the numbers is: $sum"; // Output: The sum of the numbers is: 30
?>
Example 3: User-defined Function – Calculate Factorial
Let’s create a user-defined function to calculate the factorial of a given positive integer.
<?php
function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
$number = 5;
$result = factorial($number);
echo "The factorial of $number is: $result"; // Output: The factorial of 5 is: 120
?>
Numeric Functions
Numeric functions in PHP are the functions that return numeric results.
Numeric php function can be used to format numbers, return constants, perform mathematical computations etc. A list of PHP Numeric functions that are commonly used.
Function | Description | Example | Output |
---|---|---|---|
is_number | Accepts an argument and returns true if its numeric and false if it’s not | <?php if(is_numeric(“guru”)) { echo “true”; } else { echo “false”; } ?> | false |
<?php if(is_numeric (123)) { echo “true”; } else { echo “false”; } ?> | true | ||
number_format | Used to formats a numeric value using digit separators and decimal points | <?php echo number_format(2509663); ?> | 2,509,663 |
rand | Used to generate a random number. | <?php echo rand(); ?> | Random number |
round | Round off a number with decimal points to the nearest whole number. | <?php echo round(3.49); ?> | 3 |
sqrt | Returns the square root of a number | <?php echo sqrt(100); ?> | 10 |
cos | Returns the cosine | <?php echo cos(45); ?> | 0.52532198881773 |
sin | Returns the sine | <?php echo sin(45); ?> | 0.85090352453412 |
tan | Returns the tangent | <?php echo tan(45); ?> | 1.6197751905439 |
pi | Constant that returns the value of PI | <?php echo pi(); ?> | 3.1415926535898 |
PHP String Functions
PHP provides various string functions to access and manipulate strings. A list of PHP string functions that are commonly used.
addcslashes() | It is used to return a string with backslashes. |
addslashes() | It is used to return a string with backslashes. |
bin2hex() | It is used to converts a string of ASCII characters to hexadecimal values. |
chop() | It removes whitespace or other characters from the right end of a string |
chr() | It is used to return a character from a specified ASCII value. |
chunk_split() | It is used to split a string into a series of smaller parts. |
convert_cyr_string() | It is used to convert a string from one Cyrillic character-set to another. |
convert_uudecode() | It is used to decode a uuencoded string. |
convert_uuencode() | It is used to encode a string using the uuencode algorithm. |
count_chars() | It is used to return information about characters used in a string. |
crc32() | It is used to calculate a 32-bit CRC for a string. |
crypt() | It is used to create hashing string One-way. |
echo() | It is used for output one or more strings. |
explode() | It is used to break a string into an array. |
fprint() | It is used to write a formatted string to a stream. |
get_html_translation_table() | Returns translation table which is used by htmlspecialchars() and htmlentities(). |
hebrev() | It is used to convert Hebrew text to visual text. |
hebrevc() | It is used to convert Hebrew text to visual text and new lines (\n) into <br>. |
hex2bin() | It is used to convert string of hexadecimal values to ASCII characters. |
htmlentities() | It is used to convert character to HTML entities. |
html_entity_decode() | It is used to convert HTML entities to characters. |
htmlspecialchars() | Converts the special characters to html entities. |
htmlspecialchars_decode() | Converts the html entities back to special characters. |
Implode() | It is used to return a string from the elements of an array. |
Join() | It is the Alias of implode() function. |
Levenshtein() | It is used to return the Levenshtein distance between two strings. |
Lcfirst() | It is used to convert the first character of a string to lowercase. |
localeconv() | Get numeric formatting information |
ltrim() | It is used to remove whitespace from the left side of a string. |
md5() | It is used to calculate the MD5 hash of a string. |
md5_files() | It is used to calculate MD5 hash of a file. |
metaphone() | It is used to calculate the metaphone key of a string. |
money_format() | It is used to return a string formatted as a currency string. |
nl2br() | It is used to insert HTML line breaks in front of each newline in a string. |
nl_langinfo() | Query language and locale information |
number_format() | It is used to format a number with grouped thousands. |
ord() | It is used to return ASCII value of the first character of a string. |
parse_str() | It is used to parse a query string into variables. |
print() | It is used for output one or more strings. |
printf() | It is used to show output as a formatted string. |
quoted_printable_decode() | Converts quoted-printable string to an 8-bit string |
quoted_printable_encode() | Converts the 8-bit string back to quoted-printable string |
quotemeta() | Quote meta characters |
rtrim() | It is used to remove whitespace from the right side of a string. |
setlocale() | It is used to set locale information. |
sha1() | It is used to return the SHA-1 hash of a string. |
sha1_file() | It is used to return the SHA-1 hash of a file. |
similar_text() | It is used to compare the similarity between two strings. |
Soundex() | It is is used to calculate the soundex key of a string. |
sprintf() | Return a formatted string |
sscanf() | It is used to parse input from a string according to a format. |
strcasecmp() | It is used to compare two strings. |
strchr() | It is used to find the first occurrence of a string inside another string. |
strcmp() | Binary safe string comparison (case-sensitive) |
strcoll() | Locale based binary comparison(case-sensitive) |
strcspn() | It is used to reverses a string. |
stripcslashes() | It is used to unquote a string quoted with addcslashes(). |
stripos() | It is used to return the position of the first occurrence of a string inside another string. |
stristr() | Case-insensitive strstr |
strlen() | It is used to return the length of a string. |
strncasecmp() | Binary safe case-insensitive string comparison |
strnatcasecmp() | It is used for case-insensitive comparison of two strings using a “natural order” algorithm |
strnatcmp() | It is used for case-sensitive comparison of two strings using a “natural order” algorithm |
strncmp() | It is used to compare of the first n characters. |
strpbrk() | It is used to search a string for any of a set of characters. |
strripos() | It finds the position of the last occurrence of a case-insensitive substring in a string. |
strrpos() | It finds the length of the last occurrence of a substring in a string. |
strpos() | It is used to return the position of the first occurrence of a string inside another string. |
strrchr() | It is used to find the last occurrence of a string inside another string. |
strrev() | It is used to reverse a string. |
strspn() | Find the initial length of the initial segment of the string |
strstr() | Find the occurrence of a string. |
strtok() | Splits the string into smaller strings |
strtolower() | Convert the string in lowercase |
strtoupper() | Convert the strings in uppercase |
strtr() | Translate certain characters in a string or replace the substring |
str_getcsv() | It is used to parse a CSV string into an array. |
str_ireplace() | It is used to replace some characters in a string (case-insensitive). |
str_pad() | It is used to pad a string to a new length. |
str_repeat() | It is used to repeat a string a specified number of times. |
str_replace() | It replaces all occurrences of the search string with the replacement string. |
str_rot13() | It is used to perform the ROT13 encoding on a string. |
str_shuffle() | It is used to randomly shuffle all characters in a string. |
str_split() | It is used to split a string into an array. |
strcoll() | It is locale based string comparison. |
strip_tags() | It is used to strip HTML and PHP tags from a string. |
str_word_count() | It is used to count the number of words in a string. |
substr() | Return the part of a string |
substr_compare() | Compares two strings from an offset up to the length of characters. (Binary safe comparison) |
substr_count() | Count the number of times occurrence of a substring |
substr_replace() | Replace some part of a string with another substring |
trim() | Remove whitespace or other characters from the beginning and end of the string. |
ucfirst() | Make the first character of the string to uppercase |
ucwords() | Make the first character of each word in a string to uppercase |
vfprintf() | Write a formatted string to a stream |
vprintf() | Display the output as a formatted string according to format |
vsprintf() | It returns a formatted string |
wordwrap() | Wraps a string to a given number of characters |