23 Oct 09 PHP Programming Tutorial: Function Return Values



In our last two tutorials, we’ve learned how to create our own functions and some things we can do with them. Another important thing to learn about PHP functions is how to return values. If you send a value from your function to your script, you use the return statement. In every function you create, it’s a good habit to return a value, even if this value is only a boolean (true or false). When you return a value, it sends the value back to the script and ends the function.

The most common example of return values is to show a function using the sum of two numbers, so I’ll do that here:

<?php
// This function will add two numbers and return the sum.
function add_numbers($number1,$number2) {
    $total = $number1 + $number2; // add two numbers, assign to $total variable
    return $total; // here is our return value!
}
?>

A return statement can only return one value. It is possible to return multiple values by using an array, but that is something we’ll cover another time.

So now that we’ve created our function, let’s use it!

<?php
// This function will add two numbers and return the sum.
function add_numbers($number1,$number2) {
    $total = $number1 + $number2; // add two numbers, assign to $total variable
    return $total; // here is our return value!
}
 
echo add_numbers(1,3); // This will output 4 because 1 + 3 = 4.
?>

And here’s another example with an If Statement:

<?php
// This function will add two numbers and return the sum.
function add_numbers($number1,$number2) {
    $total = $number1 + $number2; // add two numbers, assign to $total variable
    return $total; // here is our return value!
}
 
add_numbers(5,14);
 
if ($total > 10) {
    echo "Our total is greater than 10."; // Tell user the sum is greater than 10.
} else { 
    echo "Our total is less than 10."; // Tell user the sum is less than 10.
}
?>

Go back to Building PHP Scripts.

Leave a Comment