Functions
A Function is a block of code that performs a specific task.
Instead of writing same code again and again, we can use function to reuse the code.
Such type of structure improves code readability and reduces complexity that’s why it is called function.
PHP Functions
In PHP, a function is defined using the keyword function.
A function will execute only when it is called.
When we want to perform a task multiple times in a program, we can use function.
Types of Functions in PHP:
1 Built-in Functions
2 User-defined Functions
Built-in Functions:
These are the predefined functions provided by PHP.
We can directly use these functions in our program.
Example:
php
echo strlen("Hello World");
?>
The above function will return the length of the string.
User-defined Functions:
These are the functions created by the user according to requirement.
Syntax:
function function_name()
{
// code to be executed
}
Example:
";
}
greet();
?>
The above program demonstrates a simple function call.
Function with Parameters:
We can pass values to the function using parameters.
Syntax:
function function_name($param1, $param2)
{
// code
}
Example:
The above function will print sum of two numbers.
Function with Return Value:
A function can also return value using return keyword.
Syntax:
function function_name()
{
return value;
}
Example:
The above function will return square of a number.
Difference between Function with Parameter and Without Parameter
Without Parameter With Parameter
No input is passed Input values are passed
Fixed output Output depends on input
Conclusion:
Function is very useful in PHP to reuse code and perform specific task.
It makes program simple, readable and easy to manage.
