A function in PHP is a block of reusable code that performs a specific task. Instead of writing the same code multiple times, we define a function once and call it whenever needed.
Defining and Calling a Function
A function is defined using the function
keyword and is executed when called.
Syntax
function functionName() {
// Code to execute
}
functionName(); // Call the function
Example:
function greet() {
echo "Hello, welcome to PHP!";
}
greet(); // Output: Hello, welcome to PHP!
Functions can accept parameters (inputs) to work with.
function sayHello($name) {
echo "Hello, $name!";
}
sayHello("John"); // Output: Hello, John!
β $name
is a parameter, "John"
is the argument passed when calling the function.
A function can return a value instead of printing it.
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo "Sum: $result"; // Output: Sum: 8
β return
sends the result back to the caller.
If no argument is passed, the default value is used.
function greetUser($name = "Guest") {
echo "Hello, $name!";
}
greetUser(); // Output: Hello, Guest!
greetUser("Alice"); // Output: Hello, Alice!
β "Guest"
is the default value if no argument is given.
Functions can also handle arrays.
function sumArray($numbers) {
return array_sum($numbers);
}
$nums = [10, 20, 30];
echo sumArray($nums); // Output: 60
β array_sum()
calculates the sum of all elements.
πΉ When to Use Functions?
β To avoid code repetition
β To organize and structure code
β To make code reusable
β To handle complex tasks efficiently
β Functions make code cleaner and reusable.
β They can accept parameters and return values.
β Default values can be set for optional parameters.
β Functions can work with arrays and perform calculations. π