Dr Ben Warne Posted October 2, 2006 Share Posted October 2, 2006 Im new to PHP, and i find it intriguing, so i am teaching myself basic php language.However, I've hit a stumbling block with this particular bit of code, i want it to display the change in its highest format, no frills just straight codeThanks!<head><title>Vending Machine</title></head><body><h2>Vending Machine</h2><?php $price = 27; $payment = 100; $change = $payment - $price;while ($change >0) { if ($change >= 50) $result = "50"; echo "$result"; $change = $change-$result; if ($change >= 20) $result = "20"; echo "$result"; $change = $change-$result; if ($change >= 10) $result = "10"; echo "$result"; $change = $change - 10; if ($change >= 5) $result = "5"; echo "$result"; $change = $change - 5; if ($change >= 2) $result = "2"; echo "$result"; $change = $change - 2; if ($change >= 1) $result = "1"; echo "$result"; $change = $change - 1; }echo "$change";?></body></html> Quote Link to comment Share on other sites More sharing options...
thedarkwinter Posted October 2, 2006 Share Posted October 2, 2006 HiYou are missing the brackets for the if statements...while ($change >0) { if ($change >= 50) [b]{[/b] $result = "50"; echo "$result"; $change = $change-$result; [b]}[/b] if ($change >= 20) [b]{[/b] $result = "20"; echo "$result"; $change = $change-$result; [b]}[/b]etc etc... Quote Link to comment Share on other sites More sharing options...
printf Posted October 2, 2006 Share Posted October 2, 2006 There are all kinds of ways to do this, I guess the best way would depend on what you would be using the result for! Here is a simple (off the top of my head) example using a loop where (coins) are the key in figuring the correct change to give! I can think of (2) other quicker ways to do this, but I used this way so you can see the formatted result returned. Your if() blocks need a loop, so they can add the coins up as you go through the coins, form largest amount to smallest amount[code=php:0]<?// based on 1 dollars$coin = array ( 50 => '50 cent piece', 25 => 'quarter', 10 => 'dime', 5 => 'nickel', 1 => array ( 'penny', 'pennies' ) );// base$base = 100;// cost$cost = 27;// total$total = $base - $cost;$out = array ();$num = 0;if ( $total > 0 ){ foreach ( $coin AS $cn => $cv ) { if ( $total >= $cn ) { while ( $total >= $cn ) { $out[$num] += 1; $total -= $cn; } if ( $out[$num] > 1 ) { $add = ( is_array ( $cv ) ? $cv[1] : $cv . 's' ); } else { $add = ( is_array ( $cv ) ? $cv[0] : $cv ); } $out[$num] = '(' . $out[$num] . ') ' . $add; $num++; } } echo "change\r\n<br />\r\n" . implode ( "\r\n<br />\r\nand\r\n<br />\r\n", $out ); }else{ echo 'no change to give';} ?>[/code]me! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.