applelover Posted June 5, 2008 Share Posted June 5, 2008 Ok, following is the code for placing ordinal suffixes to certain variables and so I'm trying to understand how it works. $test_c = abs($ranking) % 10; $ranking_suffix = ((abs($ranking) %100 <21> 4) ? 'th' : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th')); Basically, its taking the value of $ranking and making it absolute but I've no idea what % 10, % 100, <21> 4 means. Then it runs several conditions to test this variable and assigning the relevant suffixes. How do these conditions work? ie. what does the first part preceding ":" do and if ($test_c < 4) what happens? Thanks for your guidance. Quote Link to comment Share on other sites More sharing options...
RMcLeod Posted June 5, 2008 Share Posted June 5, 2008 Ok % is the modulus symbol it gives yot the remainder when one number is divided by another e.g. 19 / 10 = 1 with a remainder of 9 in PHP $var = 19 % 10, $var is now 9. So the first line returns $test_c with the remainder of dividing a number by 10 i.e. the last digit of a given number. The next line first of all starts by finding the remainder when divided by 100 i.e. if the ranking is 36 then the remainder is 36 if it's 136 it is still 36 (it doesn't matter how many hundreds or thousands come before this number as it doesn't affect the ordinal suffix). It then takes this number and sees if it is less than 21 and greather than 4 if it is then the correct suffix to use is th as in 4th -> 20th. If not it then checks to see what the last digit is and then appends the correct suffix. The code below is a lot easier way of doing this. <?php $last = round($ranking) % 10; switch($last) { case 1: $suffix = 'st'; break; case 2: $suffix = 'nd'; break; case 3: $suffix = 'rd'; break; default: $suffix = 'th'; } echo $ranking . $suffix; ?> I used round to make sure no decimals appear, abs() does no do this if a float is supplied a float is returned. Quote Link to comment Share on other sites More sharing options...
Gamic Posted June 5, 2008 Share Posted June 5, 2008 The issue, of course, with just doing mod 10 is that you will then get cases where the numbers are wrong:"11st, 12nd and 13rd". To make sure it's correct you need to check for these special cases. 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.