To create a function in PHP, you can use the function
keyword followed by the name of the function, a list of arguments in parentheses, and a block of code in curly braces.
Here is an example of a simple function in PHP that takes two arguments and returns their sum:
function add($x, $y) {
return $x + $y;
}
$result = add(1, 2);
echo $result; // Outputs: 3
In this example, the add()
function takes two arguments $x
and $y
, and returns their sum using the return
statement. The function is then called with the arguments 1
and 2
, and the result is assigned to the $result
variable.
You can also specify default values for function arguments by using the =
operator in the argument list. For example:
function add($x, $y = 0) {
return $x + $y;
}
$result = add(1);
echo $result; // Outputs: 1
In this example, the add()
function takes two arguments $x
and $y
, but the $y
argument has a default value of 0
. If the add()
function is called with only one argument, the default value of 0
will be used for the $y
argument.