简体   繁体   中英

Echo text depending on the variable value

I've created a ratio type of PHP script for the users in my platform.

Depending on how the user interact, the $ratio variable number changes. They start off at ratio 1.00 . The lowest they can get to is 0.00 and there is no maximum, highest user currently is on 87.50 .

I want to display a message to the user depending on what range of ratio they are at.

If their $ratio is anywhere between 0.00 to 0.90 then echo this:

<p>Your ratio is very poor!</p>

If between 0.91 to 1.99 then:

<p>Your ratio is good!</p>

And finally, if between 2.00 and up, then:

<p>You are a grandmaster!</p>

I am guessing that an IF/ELSEIF statement would be the solution to this? My platform is very trafficed so I am looking for a light-weight solution that won't put my server on health support.

You can use write this function:

function getRatioMessage($ratio) {
    if ($ratio <= 0.90) {
        $message = 'Your ratio is very poor!';
    } elseif ($ratio <= 1.99) {
        $message = 'Your ratio is good!';
    } else {
        $message = 'You are a grandmaster!';
    }

    return '<p>'.$message.'</p>';
}

And then use it in following way:

echo getRatioMessage($ratio);

Try this:

<?php

$ratio = 1.8;

switch ($ratio) {
    case ($ratio >= 0 && $ratio < 0.91):
        echo 'Your ratio is very poor!';
        break;
    case ($ratio >= 0.91 && $ratio < 2):
        echo 'Your ratio is good!';
        break;
    case ($ratio >= 2):
        echo 'You are a grandmaster!';
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM