PHP Functions
A function is a reusable block of code that performs a specific task. PHP has many built-in functions, and you can also define your own using the function keyword.
Functions help you avoid repeating code, make programs easier to read, and let you organize logic into small, testable pieces. A function only runs when it is called.
function myFunction($param) {
// code
return $value;
}Defining and calling functions
A function is defined with the function keyword, a name, and parentheses for parameters. It is executed by calling its name followed by parentheses.
Returning values
The return statement sends a value back to the code that called the function and immediately ends the function's execution.
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Amy");
?>Hello, Amy!The function accepts one parameter and returns a greeting string built with it.
<?php
function add($a, $b) {
return $a + $b;
}
echo add(3, 4);
?>7add() returns the sum of its two parameters, which is then echoed.
Key points
- Functions are defined using the function keyword.
- Functions can accept parameters and return values.
- A function must be called to execute its code.
- return both sends back a value and ends the function.
