PHP Functions
Summary: PHP Functions
A PHP function is a piece of code that can be reused many times. It can take input as an argument list and return value.

In PHP, we can define
- Conditional function
- Function within Function
- Recursive function
Advantage of PHP Functions
- Code Reusability: PHP functions are defined only once and can be invoked many times, like in other programming languages.
- Less Code: It saves a lot of code because you do not need to write the logic many times. By the use of the function, you can write the logic only once and reuse it.
- Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow of the application because every logic is divided in the form of functions.
- Reducing duplication of code
- Decomposing complex problems into simpler pieces
- Improving the clarity of the code
- Information hiding
PHP User-defined Functions
We can declare and call user-defined functions easily. Let us see the syntax to declare user-defined functions.
Syntax
function functionname(){
//code to be executed
}
Note: The function name must start with a letter and underscore only like other labels in PHP. It can not start with numbers or special symbols.
PHP Functions Example
File Name: function_file.php
<?php
function myFunction(){
echo "Hello PHP Function";
}
myFunction();//calling function
?>
Output: Hello PHP Function
PHP Function Arguments
We can pass the information in the PHP function through arguments that are separated by a comma.
PHP supports
- Call by Value (default),
- Call by Reference,
- Default argument values
- Variable-length argument list.
Let us see the example to pass a single argument in the PHP function.
File Name: function_arg.php
<?php
function myFunction($user_name){
echo "Hello $user_name<br/>";
}
myFunction("Kamal");
myFunction("Sonia");
myFunction("Rani");
?>
Output:
Hello Kamal
Hello Sonia
Hello Rani
Let us see the example to pass two arguments in a PHP function.
File Name: function_args.php
<?php
function getRecord($username,$age){
echo "Hello $username, you are $age years old<br/>";
}
getRecord("Kamal",27);
getRecord("Sonia",18);
getRecord("Shivani",23);
?>
Output:
Hello Kamal, you are 27 years old
Hello Sonia, you are 18 years old
Hello Shivani, you are 23 years old
PHP Function: Default Argument Value
We can specify a default argument value in the function. While calling PHP function if you do not specify any argument, it will take the default argument. Let us see a simple example of using the default argument value in the PHP function.
Example of default Argument Value
PHP Function: Returning Value
Let us see an example of PHP function that returns a value.
File Name: function_defaultarg.php
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output: Cube of 3 is: 27
