Functions in PHP are blocks of reusable code that perform a specific task. They help make your code modular, reusable, and easier to debug. In this tutorial, we’ll explore how to create and use functions in PHP.
To define a function in PHP, use the function
keyword followed by the function name and parentheses:
<?php
function sayHello() {
echo "Hello, World!";
}
?>
To execute the code inside a function, simply call it by its name followed by parentheses:
<?php
sayHello(); // Output: Hello, World!
?>
You can pass data into a function using parameters:
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("Alice"); // Output: Hello, Alice!
?>
Functions can return a value using the return
statement:
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo "The result is: $result"; // Output: The result is: 8
?>
You can specify default values for parameters, which are used if no value is provided when the function is called:
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
?>
PHP allows you to create functions that accept a variable number of arguments using ...
(splat operator):
<?php
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // Output: 10
?>
PHP supports anonymous functions (also known as closures), which are functions without a name:
<?php
$greet = function($name) {
echo "Hello, $name!";
};
$greet("Alice"); // Output: Hello, Alice!
?>
Practice creating your own functions with different parameters and return types. Functions are a powerful tool for organizing and reusing code in PHP applications.