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
https://forums.phpfreaks.com/topic/108811-please-explain-how-this-code-works/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.