The PHP Return Statement

The PHP Return Statement
The PHP return statement is used to tell a PHP function to send information back to the calling program. This can be useful in many ways. For example, you can use a function to calculate the sales tax for a shopping cart program. Let's use a factious online business for our example.

This business has an online store and three brick and mortar storefronts in Indiana, Ohio and Maine. This means that sales tax must be calculated for online purchases by customers in these three states. We will use our function to do the calculation. When we call the function, we will need to pass it some information (called arguments). We will pass the total dollar amount of the customer's purchase ($purchases) and the percent sales tax ($sales_tax) for each transaction. We know which state the customer lives in because he gave us that information when he opened his customer account. The function will calculate the amount of sales tax for this purchase and pass that value back to the shopping cart program. Let's take a look at the code. For our example below the total dollar amount of the purchase is $100 and the percent sales tax is .05.

function caltax($purchases, $sales_tax)
{
$result = $purchases * $sales_tax;
return $result;
}

function caltax($purchases, $sales_tax)
The function statement and function name (caltax) begins the function code. Inside the parenthesis, the $purchases variable holds the dollar amount for the transaction ($100) and the $sales_tax variable holds the percentage sales tax (.05). You may be asking why we need to pass the sales tax information each time we call the function. Remember that this company has brick and mortar stores in three states and we need to tell the function which percentage to use each time. If the customer lives in Ohio or Indiana, the percentage would be .06. In Maine, the percentage is .05.

{
Opening curly bracket

$result = $purchases * $sales_tax;
This code will multiply the dollar amount of sales and percent of sales tax. The total amount of sales tax to be collected is $5. This value is stored in the $result variable.

return $result;
The return statement ends the function and sends the value of the $result variable back to the shopping cart program.

}
Closing curly bracket






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.