A function is a block of code that can be defined and then called to perform a specific task. It helps in organizing code into modular and reusable, making it easier to manage and maintain.
It is very simple to create a php function. The syntax for declaring and calling functions in PHP is:
<?php
function name()
{
// code to be executed
}
?>
<?php
function output()
{
echo "Hello Learners";
}
?>
For calling a function just call it by using its name followed by parentheses.
<?php
function name()
{
// code to be executed
}
name(); //calling a function
?>
<?php
function output(){
echo "Hello Learners";
}
output(); // calling function
?>
Php functions has an option to pass information through arguments. An argument is like a variable.
When we define a function, we can specify parameters, which act as placeholders for values that the function will receive when it's called. These parameters are declared in the function's parentheses.
<?php
// Function definition with parameters
function name($parameter1, $parameter2, /* ... other parameters */)
{
// Function body, where you can use $parameter1, $parameter2, etc.
// Perform operations or return a value if needed
}
// Example usage
$value1 = /* some value */;
$value2 = /* some value */;
// Call the function with arguments
name($value1, $value2 /*, ... other arguments */);
?>
<?php
// Function definition with parameters
function multiply($a, $b) {
$product = $a * $b;
echo "The product of $a and $b is: $product";
}
// Example usage
$value1 = 5;
$value2 = 10;
// Call the function with arguments
multiply($value1, $value2);
?>
Note: You can have functions with zero parameters (no parameters), one parameter, two parameters, and so on, separated with comma.
We can assign default values to function parameters. If a value is not provided when the function is called, the default value will be used. This is useful when you want to make certain parameters optional.
<?php
// Function with default argument values
function greet($name = "LearnCoding", $greeting = "Hello") {
echo "$greeting, $name!";
}
// Example usage
greet(); // Uses default values: "LearnCoding" and "Hello"
echo "<br>";
greet("John"); // Uses default value for $greeting: "Hello"
echo "<br>";
greet("Geek", "Good morning"); // Uses provided values:"Geek" and "Good morning"
?>
A function can return a value using the ‘return’ statement in the function. The value returned by the function can be used in the calling code.
<?php
// Function that returns the sum of two numbers
function addNumbers($a, $b) {
$sum = $a + $b;
return $sum;
}
// Example usage
$result = addNumbers(5, 10);
// Print the result
echo "The sum is: $result";
?>
Did you Know?
Php has over 1,000 built-in functins that can be called directly.