Adding Two Numbers in PHP Using Function

Adding Two Numbers in PHP Using Function. In this program, we can print the PHP program to print the addition of two numbers using function. Other programming languages’ functions are similar to PHP’s. A function is a piece of code that takes another input in the form of a parameter, processes it, and then returns a value. Although these are built-in functions, PHP also allows you to construct your own.

<?php
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "4 + 5 = " . sum(4,5) . "<br>";
echo "5 + 2 = " . sum(5,2) . "<br>";
echo "2 + 8 = " . sum(2,8);
?>

 

Output:

4 + 5 = 9
5 + 2 = 7
2 + 8 = 10

Function in PHP

In PHP, a function is a reusable chunk of code that performs a specific task. It takes user input in the form of parameters, performs certain actions, and then outputs the results. When called, functions can either return values or simply perform an operation without returning anything. 

A constant is defined by the define() function. Constants are similar to variables, with the following exceptions: The value of a constant cannot be changed once it has been set. A leading dollar sign ($) is not required for constant names. Regardless of scope, constants can be accessed. Using this kind of functions to execute addition of two number using function in php.

Return Statement in PHP

A return statement marks the end of a function’s execution and hands control back to the calling function. The calling function resumes execution at the point where the call was made. A return statement can give the calling function a value.