How to define a function in PHP?

Member

by dedrick , in category: PHP General , 6 months ago

How to define a function in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 6 months ago

@dedrick 

In PHP, you can define a function using the function keyword, followed by the function name, and the parameters that the function takes (if any). Here is an example of a function that takes two parameters and returns their sum:

1
2
3
function sum($num1, $num2) {
    return $num1 + $num2;
}


In this example, the function name is sum, and it takes two parameters $num1 and $num2. The return keyword is used to return the sum of the two parameters.


You can then call this function by passing in two arguments:

1
2
$result = sum(2, 3);
echo $result; // Outputs 5


In this example, the sum function is called with the arguments 2 and 3, and the result is stored in the variable $result. Finally, the value of $result is printed to the screen using the echo statement.