User-Defined Functions are functions created by the PHP programmer to encapsulate a specific block of code and give it a name. These functions are defined by the user to perform a particular task or set of tasks. They contribute to code organization, reusability, and maintainability.
Examples:
<?php
// User-Defined Function to add two numbers
function addNumbers($num1, $num2) {
return $num1 + $num2;
}
// Calling the function
$result = addNumbers(5, 10);
echo $result;
?>
Output: 15
In this example:
- We define a function named addNumbers that takes two parameters ($num1 and $num2).
- The function body contains the code to add the two numbers, and the result is returned using the return statement.
- We then call the function with arguments 5 and 10, and the result is stored in the $result variable and echoed to the screen.