Porl123 Posted September 16, 2009 Share Posted September 16, 2009 I've just started using case switch instead of if else and already I'm having problems I was wondering if there's something wrong with this: function wealth_status($money) { switch($money) { case($money >= 0 && $money < 100000): return 'Very Poor'; break; case($money >= 100000 && $money < 350000): return 'Poor'; break; case($money >= 350000 && $money < 1000000): return 'Worker'; break; case($money >= 1000000 && $money < 3000000): return 'Saver'; break; case($money >= 3000000 && $money < 6500000): return 'Investor'; break; case($money >= 6500000 && $money < 10000000): return 'Wealthy'; break; case($money >= 10000000 && $money < 25000000): return 'Rich'; break; case($money >= 25000000 && $money < 50000000): return 'Very Rich'; break; case($money >= 50000000 && $money < 100000000): return 'Filthy Rich'; break; case($money >= 100000000): return 'Notoriously Rich'; break; default: return 'Invalid Wealth'; break; } } I've got this function that returns the value 'Poor' when the $money variable is 0 and it should be 'Very Poor'. Anybody know why? any help will be appreciated! Thanks Link to comment https://forums.phpfreaks.com/topic/174464-case-switch/ Share on other sites More sharing options...
ILMV Posted September 16, 2009 Share Posted September 16, 2009 You should do this: function wealth_status($money) { switch($money) { case($money < 100000): $output='Very Poor'; break; case($money < 350000): $output='Poor'; break; case($money < 1000000): $output='Worker'; break; case($money < 3000000): $output='Saver'; break; case($money < 6500000): $output='Investor'; break; case($money < 10000000): $output='Wealthy'; break; case($money < 25000000): $output='Rich'; break; case($money < 50000000): $output='Very Rich'; break; case($money < 100000000): $output='Filthy Rich'; break; case($money >= 100000000): $output='Notoriously Rich'; break; default: $output='Invalid Wealth'; break; } return $output; } Link to comment https://forums.phpfreaks.com/topic/174464-case-switch/#findComment-919522 Share on other sites More sharing options...
Daniel0 Posted September 16, 2009 Share Posted September 16, 2009 You can do it in a much more clever way: <?php $wStatuses = array( array('min' => 0, 'title' => 'Very poor'), array('min' => 100000, 'title' => 'Poor'), array('min' => 350000, 'title' => 'Worker'), // etc. ); $money = 105032; $i = 0; $next = 1; while (isset($wStatuses[$next]) && $wStatuses[$next]['min'] < $money) { $i = $next++; } echo 'Having ' . $money . ' money, your wealth status is: ' . $wStatuses[$i]['title']; This makes it much easier adding additional wealth statuses. Link to comment https://forums.phpfreaks.com/topic/174464-case-switch/#findComment-919525 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.