OneBite.Dev - Coding blog in a bite size

Declare A Function With Return Value In PHP

Code snippet for how to Declare A Function With Return Value In PHP with sample and detail explanation

In PHP, a function is a block of code that performs a specific task. It can be designed to return a value when called within a script. Let’s figure out how to declare a function with a return value in PHP.

Code snippet

Here’s a simple example on how to declare a function in PHP which returns a value:

function add($num1, $num2){
  $sum = $num1 + $num2;
  return $sum;
}

echo add(5, 3); 

In the above code snippet, we have declared a function called ‘add’. This function takes two parameters, $num1 and $num2, and returns their sum.

Code Explanation

Decoding the code snippet in a step-by-step manner, here’s what each part does:

  1. The PHP script begins with the keyword function which is used to declare a function in PHP.

  2. add is the name given to the function. When creating your own functions, you can name them as you want but they should preferably be descriptive about what the function does.

  3. ($num1, $num2) is the parameter list in the function definition. These are inputs to the function. When you call the function, you provide the values for these parameters.

  4. Within the curly brackets {}, we have the code block of the function. This is where the actual task of the function is performed. In this function, we are calculating the sum of $num1 and $num2.

  5. Next, we have the return statement which ends the function execution and optionally returns an expression. In our case, it’s returning the sum of the input numbers.

  6. The part echo add(5, 3); is where we call the function. add(5, 3) refers to calling the function add with values 5 and 3 passed as arguments. These values are then used within the function for our calculations. The echo is used to output the result.

In conclusion, declaring a function with a return value in PHP is straightforward. Just remember to use the return statement to specify what value or result you want the function to output. Following this tutorial, you should now be well-equipped to experiment with your own PHP functions.

php