PHP: Returning an array in a function

This entry is part 34 of 54 in the series PHP Tutorial

Returning an array is actually quite simple with return array().

We just have to pass the 2 amounts into the array() function with

return array($total_notip, $total_tip);

The 2 array elements will then be accessible by $totals[0] and $totals[1].


function restaurant_check($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);

$totals = restaurant_check(30.50, 7, 15);

echo "The total without tip is $totals[0]";
echo "\n";
echo "The total with tip is $totals[1]";

Series Navigation<< PHP: Returning a value from a function
PHP: Test a function >>

Leave a comment

Leave a Reply