How to define a function in PHP?

Member

by dedrick , in category: PHP General , 2 years ago

How to define a function in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by addison , 2 years 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.

Member

by samara , a year ago

@dedrick 

Another way to define a function in PHP is by using the arrow function syntax, available from PHP 7.4 onwards. Here's an example:

1
$sum = fn($num1, $num2) => $num1 + $num2;


In this case, the function name is not explicitly defined, and you can assign the function definition directly to a variable. The function takes two parameters, $num1 and $num2, and returns their sum. This arrow function syntax is a more concise way of defining functions, especially for smaller and simpler functions.


To call this function, you can do the following:

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


The $sum variable represents the function definition, and you can use it as a regular function by passing in arguments and assigning the result to a variable.