Groups of Logic: Returning Values from Functions in PHP

The header-printing function you’ve seen in this chapter takes action by displaying some output. In addition to an action such as printing data or saving information into a database, functions can also compute a value, called the return value, which can be used later in a program. To capture the return value of a function, assign the func­tion call to a variable. Example 5-10 stores the return value of the built-in function number_fomat() in the variable $number_to_display.

Example 5-10. Capturing a return value

$number_to_display = number_format( 12144201 );

print “The population of the US is about: $number_to_display”;

Just like Example 1-6, Example 5-10 prints:

The population of the US is about: 321,442,019

Assigning the return value of a function to a variable is just like assigning a string or number to a variable. The statement $number = 57 means “store 57 in the variable $number” The statement $number_to_display = number_fomat(321442019) means “call the number_fomat() function with the argument 321442019 and store the return value in $number_to_display” Once the return value of a function has been put into a variable, you can use that variable and the value it contains just like any other variable in your program.

To return values from functions you write, use the return keyword with a value to return. When a function is executing, as soon as it encounters the return keyword, it stops running and returns the associated value. Example 5-11 defines a function that returns the total amount of a restaurant check after adding tax and tip.

Example 5-11. Returning a value from a function

function restaurant_check($meal, $tax, $tip) {

$tax_amount = $meal * ($tax / 10 );

$tip_amount = $meal * ($tip / 10 );

return $total_amount;

}

The value that restaurant_check() returns can be used like any other value in a pro­gram. Example 5-12 uses the return value in an if() statement.

Example 5-12. Using a return value in an if() statement

// Find the total cost of a $15.22 meal with 8.25% tax and a 15% tip

$total = restaurant_check(15.22, 8.25, 15);

print ‘I only have $20 in cash, so…’;

if ($total > 20) {

print “I must pay with my credit card.”;

} else {

print “I can pay with cash.”;

}

A particular return statement can only return one value. You can’t return multiple values with something like return 15, 23. If you want to return more than one value from a function, you can put the different values into one array and then return the array.

Example 5-13 shows a modified version of restaurant_check() that returns a two- element array containing the total amount before the tip is added and after it is added.

Example 5-13. Returning an array from a function

function restaurant_check2($meal, $tax, $tip) {

$tax_amount = $meal * ($tax / 100);

$tip_amount = $meal * ($tip / 100);

$total_notip = $meal + $tax_amount;

$total_tip = $meal + $tax_amount + $tip_amount;

return array($total_notip, $total_tip);

}

Example 5-14 uses the array returned by restaurant_check2().

Example 5-14. Using an array returned from a function

$totals = restaurant_check2(15.22, 8.2 , 15);

if ($totals[0] < 20) {

print ‘The total without tip is less than $20.’;

}

if ($totals[1] < 20) {

print ‘The total with tip is less than $20.’;

}

Although you can only return a single value with a return statement, you can have more than one return statement inside a function. The first return statement reached by the program flow inside the function causes the function to stop running and return a value. This isn’t necessarily the return statement closest to the begin­ning of the function. Example 5-15 moves the cash-or-credit-card logic from Example 5-12 into a new function that determines the appropriate payment method.

Example 5-15. Multiple return statements in a function

function payment_method($cash_on_hand, $amount) {

if ($amount > $cash_on_hand) {

return ‘credit card’;

} else {

return ‘cash’;

}

}

Example 5-16 uses the new payment_method() function by passing it the result from restaurant_check().

Example 5-16. Passing a return value to another function

$total = restaurant_check( 15.22;, 8.2 , 15  );

$method = payment_method(20, $total);

print ‘I will pay with ‘ . $method;

Example 5-16 prints the following:

I will pay with cash

This is because the amount restaurant_check() returns is less than 20. This is passed to payment_method() in the $total argument. The first comparison in payment_method(), between $amount and $cash_on_hand, is false, so the code in the else block inside payment_method() executes. This causes the function to return the string cash.

The rules about truth values discussed in Chapter 3 apply to the return values of functions just like other values. You can take advantage of this to use functions inside if() statements and other control flow constructs. Example 5-17 decides what to do by calling the restaurant_check() function from inside an if() statement’s test expression.

Example 5-17. Using return values with if()

if (restaurant_check(15.22 , 8.25, 15) < 20) {

print ‘Less than $20, I can pay cash.’;

} else {

print ‘Too expensive, I need my credit card.’;

}

To evaluate the test expression in Example 5-17, the PHP engine first calls the restaurant_check() function. The return value of the function is then compared with 20, just as it would be if it were a variable or a literal value. If restau rant_check() returns a number less than 20, which it does in this case, then the first print statement is executed. Otherwise, the second print statement runs.

A test expression can also consist of just a function call with no comparison or other operator. In such a test expression, the return value of the function is converted to true or false according to the rules outlined in “Understanding true and false” on page 40. If the return value is true, then the test expression is true. If the return value is false, so is the test expression. A function can explicitly return true or false to make it more obvious that it should be used in a test expression. The can_pay_cash() function in Example 5-18 does this as it determines whether we can pay cash for a meal.

Example 5-18. Functions that return true or false

function can_pay_cash($cash_on_hand, $amount) {

if ($amount > $cash_on_hand) {

return false;

} else {

return true;

}

}

$total = restaurant_check(15.22,8.25, 15);

if (can_pay_cash(20, $total)) {

print “I can pay in cash.”;

} else {

print “Time for the credit card.”;

}

In Example 5-18, the can_pay_cash() function compares its two arguments. If $amount is bigger, then the function returns true. Otherwise, it returns false. The if() statement outside the function single-mindedly pursues its mission as an if() statement—finding the truth value of its test expression. Since this test expression is a function call, it calls can_pay_cash() with the two arguments 20 and $total. The return value of the function is the truth value of the test expression and controls which message is printed.

Just like you can put a variable in a test expression, you can put a function’s return value in a test expression. In any situation where you call a function that returns a value, you can think of the code that calls the function, such as restaurant_check(15.22,8.25,15), as being replaced by the return value of the function as the program runs.

One frequent shortcut is to use a function call with the assignment operator in a test expression and to rely on the fact that the result of the assignment is the value being assigned. This lets you call a function, save its return value, and check whether the return value is true all in one step. Example 5-19 demonstrates how to do this.

Example 5-19. Assignment and function call inside a test expression

function complete_bill($meal, $tax, $tip, $cash_on_hand) {

$tax_amount = $meal * ($tax / 100);

$tip_amount = $meal * ($tip / 100);

$total_amount = $meal + $tax_amount + $tip_amount;

if ($total_amount > $cash_on_hand) {

// The bill is more than we have

return false;

} else {

// We can pay this amount

return $total_amount;

}

}

if ($total = complete_bill(15.22, 8.25, 15, 20)) {

print “I’m happy to pay $total.”;

} else {

print “I don’t have enough money. Shall I wash some dishes?”;

}

In Example 5-19, the complete_bill() function returns false if the calculated bill, including tax and tip, is more than $cash_on_hand. If the bill is less than or equal to $cash_on_hand, then the amount of the bill is returned. When the if() statement outside the function evaluates its test expression, the following things happen:

  1.   complete_bill() is called with arguments 15.22, 8.25, 15, and 20.
  2. The return value of complete_bill() is assigned to $total.
  3. The result of the assignment (which, remember, is the same as the value being assigned) is converted to either true or false and used as the end result of the test expression.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *