☜
☞
create
To create a function in PHP, you can use the function keyword followed by the name of the function and a set of parentheses. The code that makes up the function should be enclosed in curly braces. Here is an example of a simple function in PHP:
function greet($name) {
echo "Hello, $name!";
}
This function takes a single argument, $name, and outputs a greeting using the value of $name. To call this function, you can use the function name followed by a set of parentheses and the required arguments:
greet('John'); // Outputs: "Hello, John!"
You can also specify a default value for function arguments by using the = operator in the function definition. If a default value is provided, the argument is optional when calling the function. For example:
function greet($name = 'world') {
echo "Hello, $name!";
}
greet(); // Outputs: "Hello, world!"
greet('John'); // Outputs: "Hello, John!"
You can also return a value from a function using the return keyword. For example:
function add($x, $y) {
return $x + $y;
}
$sum = add(1, 2); // $sum is now 3
☜
☞