Jump to content

Please explain how this code works


applelover

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.