Functions in PHPWe can use a function in PHP to execute a specific task or a set of tasks. Function is used when a specific code is used again and again. It is better to keep the code inside a function and call the function to perform the same task. We can pass variables to a function and after processing the function will return the value to the main script.
Function is a set of or block of code to do a particular task.
PHP built-in functionsBased on the common tasks required PHP has built in functions available at script level to use. These functions need not be declared and can directly used. Some common examples are string functions, math function and other basic functions to develop scripts.
User defined functionsWe can write code and define function for our use in our scripts, we will learn more about these functions here. We will learn how to declare a function, pass a variable or an array and how to return variables or array to main script or calling script. Let us see how to define a function.
You can see above we have kept the code inside a function and call it from our main script. Two variables we have passed to the function and displayed them using print command. Here print is a built-in function of PHP.
Testing function support.We can check if the function support is available or not by using function_exists() function. This function returns TRUE if function is available or else FALSE.
Here is a sample script using function_exists()
Returning value from a Functions to main scriptNow let us modify the function we discussed and see how we can return value from a php function to our main script. Here we will send three numeric values to the function and get back the sum of the three values in our main script. Here the function will receive three arguments or variables and process it. We will use return command to return the end result to the main script from the function.
We have seen here how the value is returned to the main calling script by using return command. To access the variables declared in the main script inside the function, we have to declare them as global inside the function.
This article is written by plus2net.com team.