advertisement
Function and Array in PHP
Introduction to Function
Functions can be defined as a named section of a program that performs a specific task. Functions enable to split of a program into modules. It avoids repeating codes that have already been written. Any modification in codes has to be done only once rather than multiple times. Thus, it is quick and easy to modify a program containing functions.
Functions
Sometimes in a program, there are blocks of code that are used repetitively. Instead of writing the same code several times, the function can be used. A function groups together several statements into a single unit. This group of statements performs a specific task. It enables developers to reuse the same piece of code in the program without typing it again.
Functions help in organizing a program, that is, they enhance the logical flow in a program by dividing complicated code sequences into smaller modules. Any software module is always part of a program. Programs consist of one or several modules that are developed independently and are combined only when the program is linked. A single module can contain one or more routines. Functions enable writing a piece of code and assigning a name for it. The function can be executed or invoked using the assigned name anywhere in the program.
parameters are included within a function to add more functionality, parameters are like variables and are specified within the parentheses after the name of a function.
- PHP provides different built-in functions.
- PHP also allows one to define a function. create a function, and design a specific task for it.
- These functions are known as user-defined functions.
Built-in PHP Functions
PHP provides various built-in functions that can be grouped into the following categories:
- Mathematical Functions
- String Functions
- Date and Time Functions
- Error Handling Functions
- Database Functions
- Array Functions
- Mail Functions
Built-in functions can be included in this PHP script.
1. Mathematical Functions:-
Mathematical Functions operate on numerical data.
Function Name | Syntax | Description
- Abs | abs(arg) | Returns the absolute value of the argument.
- Max | max(arg1,arg2,.) | Returns the largest value from the specified arguments. It also allows comparing multiple arrays.
- Min | min(arg1,arg2,.) | Returns the smallest value from the specified arguments. It also allows for comparing multiple arrays.
- Sqrt | sqrt(arg) | Returns the square root of the argument.
- pow | pow(base,exp) | Returns the value of the base raised to the power of the exponential.
- Round | round(number) | Returns the nearest integer of the specified number.
- rand() | rand(min,max) | Returns a random integer.
- ceil() | ceil(X) | Returns the value of a number rounded upwards to the nearest integer.
- floor() | floor(X) | Returns the value of a number rounded downwards to the nearest integer.
2. String Functions:-
String functions operate on the character type of data. It allows the developers to manipulate strings.
Name | General Form | Description
- Chr | chr(ascii) | Returns the character equivalent to the specified ASCII code.
- bin2hex | bin2hex(string) | Converts a string of ASCII characters to hexadecimal values.
- strtolower | strtolower(string) | Converts the specified string to lowercase.
- strlen | strlen(string) | Returns the length of the string specified as an argument.
- strcmp | strcm(string1,string2) | Compares two strings. Returns zero ifstring1 is equal to string2. It returns less than zero if string1 is less than string2. Otherwise, it returns greater than zero when string1 is greater than string2
- strtoupper | strtoupper(string) | Converts the specified string to uppercase.
- strrev | strrev(string) | Returns the reverse of the string.
- stristr() | stristr(string, search) | Finds the first occurrence of a string inside another string (case-insensitive).
- strrpos() | strrpos(string,find,start) | Finds the position of the last.
- ... | ... | occurrence of a string inside another string (case-sensitive).
- strncmp() | strncmp(string1,string2, length) | Performs string comparison of the first n characters (case-sensitive).
3. Date & Time Functions:-
Date and time functions enable to calculation of the date and time on the system. Allows to extract and format the date and time on the server.
Function Name | Syntax | Description
- checkdate | checkdate(month, day, year) | Returns the value as 1 if the specified date is valid.
A valid date contains:
a) a month between 1 and 12
b) day within the range of days for the specified month
c) year between 1 and 32767 - getdate | getdate(timestamp) | Returns an array containing date and time information. The information is returned for a Unix timestamp.
- time | time() | Returns the current time measured in the number of seconds.
- strtotime | strtotime(string time[,now]) | Parses an English textual date or time into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
- date | date(format, timestamp) | Returns a string depending on the timestamp or the current local time, if the timestamp is not specified
Some of the formats that can be used are as follows:
d-day of the month
D-textual representation of the day
j-day of the month without leading zeros (1 to 31)
m-numeric representation of the month M-textual representation of the month y - a two-digit representation of the year Y - a four-digit representation of the year a - Lowercase am or pm
h - 12-hour format of an hour H - 24-hour format of hour i- minutes with leading zeroes-seconds with leading zeros
4. Error Handling Functions:-
Error handling is the process of troubleshooting errors as they arise during the execution of a program.
PHP provides error-handling functions to define the error-handling rules and modify the way the errors are handled.
Function Name | General Form | Description
- trigger_error | trigger_error(error_msg [,error_type]) | Generates an error message, that is, it defines an error-specified message at the condition as specified by the user. User-defined functions such as asset_error_handler() inbuilt error handler can be used with it.
- set_error_handler | set_error_handler(error_handler) | Handles errors during runtime by using a user-defined function.
- error_reporting | error_reporting(constant) | Specifies which PHP errors are reported. PHP provides many levels of errors. You can use this function to set a level during the run-time of the script.
The error_reporting() function requires constant arguments
Constant Name | Value | Description
- E_ERROR | 1 | Displays errors that are not recoverable
- E_WARNING | 2 | Displays non-fatal run-time errors, however, this does not halt the execution of the script.
- E_PARSE | 4 | Displays errors generated by the parser during compilation.
- E_NOTICE | 8 | Displays run-time error notices
- E_COMPILE_ERROR | 64 | Displays compile-time errors
- E_USER_ERROR | 256 | Displays the user-generated error message
- E_USER_WARNING | 512 | Displays user-generated warning message
- E_CORE_ERROR | 16 | Displays fatal errors during PHP start-up
- E_CORE_WARNING | 32 | Displays non-fatal errors during PHP start-up
- E_COMPILE_WARNING | 128 | Displays errors generated by Zend Scripting Engine
- E_ALL | 8191 | Displays all errors and warnings that are supported
User-defined Functions
The function can also be defined or created. A function has to be defined before it can be used. The function definition contains the code to be executed.
Passing Arguments to Functions
PHP supports the passing of arguments to a function. Three different ways of passing arguments to a function are as follows:
- Passing arguments by value
- Passing arguments by reference
- Setting default values for arguments
1. Passing arguments by value:-
When an argument is passed to the function as a value, the value of the argument remains unchanged outside the function. The arguments are prefixed with the dollar($) sign in the function definition to indicate that the argument will be passed by the value. The argument can be any valid expression, the expression is evaluated, and its value is assigned to the corresponding variable in the function.
2. Passing arguments by reference:-
Values can be passed to the argument by reference. When a value is passed by reference to the argument, the value of the argument changes outside the function. While defining a function, prefix the arguments with the ampersand (&) sign to indicate that the value is passed by reference. When an argument is passed to a function by reference, the argument must be available. When the value of the variable is modified within a function, the instance of the variable outside the function is also modified. The arguments must be passed to a function by reference to enable the function fo to modify the argument. The ampersand (&) symbol is prefixed for the argument name in the function definition to pass an argument to the function by reference.
3. Setting default values for arguments:-
Default values can also be assigned to the arguments. The default values for the argument must be assigned in the function definition. The function would process only the default value when a default value is defined for the argument in the function definition. PHP enables the assignment of default values to an argument in a function. The default values enable the developer to initialize the function parameters when the function is invoked without any value being passed.
The default value assigned can be any one of the following:
- Constant
- Scalar
- Array with scalar values or constant
Returning Values from Functions
A function can also return values. The return statement in a function returns the value from the function. The value returned can be an array or an object. The return keyword causes the function to stop execution and pass the control to the line from which it was invoked. It is essential to Use the reference operator & while declaring a function as well as when assigning the returned value to the variable. This is required to return a reference from a function.
Nesting of Functions
There can be different functions in a program. One function can be dependent on another function in the program. When one function is being executed, it can call or execute another function. The execution of one function inside another function is called the nesting of functions.
Recursion
The execution of a function within another function is called a nested function. When a function executes itself repeatedly it is known as recursion. When a function calls itself, the same block of code is executed.
Introduction to Arrays
programming languages use variables to store values. An array is a variable that can store a list of values. ATays can be single-dimensional or multi-dimensional. All the values are referred to by the same array name.
Defining an Array
Each value in an array is termed an element. All elements in an array are referenced by a common name. Each element of an array can be referred to by an array name and an index. An array index is used to access an element. An index can be a number or a string. If the index is a string. the aTay is an associatve aray. If the index is a number, there's an indexed array. By default, the index value in an array starts at zero. As a result, the index number of the last element in an aTay is one less than the total number of elements. For example, in any of the five elements, the index number of the last element will be four.`
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0