Search code examples
phpfunctionranking

How would i add 'No Data' to this php function?


I have written a PHP function to add the appropriate stems to each rank. I.E. 1st 2nd 3rd... so on and so forth.

When $num = 0 the displayed result is "0th", is there a way to display this a 'No Data' instead?

function ordinalSuffix($num) {
    $suffixes = array("st", "nd", "rd");
    $lastDigit = $num % 10;

    if(($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3) return "th";

    return $suffixes[$lastDigit - 1];
}

Solution

  • Like this?

    function ordinalSuffix($num) {
        //Check if $num is equal to 0
        if($num == 0){
            //return
            return 'No Data';
        }
        $suffixes = array("st", "nd", "rd");
        $lastDigit = $num % 10;
    
        if(($num < 20 && $num > 9) || $lastDigit == 0 || $lastDigit > 3) return "th";
    
        return $suffixes[$lastDigit - 1];   
    }