PHP: Help

Random Quote Generator

-

<a id=“tweet” href="“https://twitter.com/intent/tweet”" title=“Tweet this!”>

<div class= "new-quote-button" >
<button class="button" id="new-quote"> New Quote
</div>

You have many issues.

1.) you are defining $cash_on_hand twice.
2.) you are missing semi-colon in $tip_percent variable
3.) you are checking $cash_on_hand to the value of 35 (its initial value, but it never gets updated)
4.) you are checking $cash_on_hand to a card coded value/static value… instead of checking it against the total cost.
5.) You are checking if $cash_on_hand is LESS THAN something. (don’t you want the opposite?)
6.) you aren’t updating the total cost anywhere in your loop (just the tip%)

maybe something like this:

//set initial values
$cash_on_hand = 35;
$meal = 30;
$tip_percent = 10;
//set initial total cost
$cost = $meal + ($meal* ($tip_percent/100));

echo 'Cash On Hand: ' . $cash_on_hand . '<br>';
echo 'Meal Cost: ' . $meal . '<br>';
echo 'Tip %: ' . $tip_percent . '<br>';
echo 'Total Cost: ' . $cost . '<br><br>';


while($cash_on_hand >= $cost) {
	$formattedCost = number_format($cost, 2);
	echo "I can afford a tip of $tip_percent%, for Total Cost: $$formattedCost <br/>";
	//update tip
	$tip_percent++; 
	
	//update total cost (with increased tip %)
	$cost = $meal + ($meal* ($tip_percent/100));
}

Output:

Cash On Hand: 35
Meal Cost: 30
Tip %: 10
Total Cost: 33

I can afford a tip of 10%, for Total Cost: $33.00
I can afford a tip of 11%, for Total Cost: $33.30
I can afford a tip of 12%, for Total Cost: $33.60
I can afford a tip of 13%, for Total Cost: $33.90
I can afford a tip of 14%, for Total Cost: $34.20
I can afford a tip of 15%, for Total Cost: $34.50
I can afford a tip of 16%, for Total Cost: $34.80
1 Like

Hi,

Thank you so much for your suggestions! As a beginner, the loops for PHP has been very confusing but I was able to fix my code and successfully run it. Thanks again!

Sponsor our Newsletter | Privacy Policy | Terms of Service