Functions in PHP With Examples
In this article, we will see about functions in PHP with examples.
What are PHP functions?
- A function is a block of code with a name, meant to perform a specific task.
- Whenever we want to perform a specific task, we create a function.
How to create a function
A function is created or defined with the help of the function keyword.
Syntax:
function functionname([param1, param2,...param N]) // function header
{
statement(s) to be executed;
[return returning value;]
}
Ex: a function without parameters, without returning value
function wish()
{
echo "Hi", "<br/>";
}
Note: Every Function get execute only when we call them
The syntax for function call:
functionname([param1, param2,...paramN]);
Example:
wish(); //HI
Why function is created
- for manageability(i.e. to divide a larger problem into smaller tasks or modules)
- for reusability (i.e. once a function is defined, it can be used multiple times)
- for abstraction (i.e. hiding the way how tasks are done) (creating libraries)
Ex:
wish() // HI
wish() // HI
wish() // HI
Function with parameters and returning value
function add(a, b)
{
return a+b;
}
echo add(5,5) // 10
echo add(5,10) // 15
/*output:
10
15
*/
Here, we have created add() function by passing two arguments namely (a, b). Within the add() function, we return the added value of “a and b”. Finally, we call the add() function by passing two parameters i.e (5, 5), so the output is displayed as 5+5 =10.