Matt Cowley Matt Cowley - 6 months ago 13
PHP Question

Multiple If Condensing - PHP

So I have this code... (I'm sorry)

(I needed more "details" in my question as the code is so long)
Basically it takes the users hug count, and at intervals it gives them a new quote as a reward, but the intervals are irregular.

if ($hugs > 0) {
$quote = $quotes[0];
}
if ($hugs > 5) {
$quote = $quotes[1];
}
if ($hugs > 10) {
$quote = $quotes[2];
}
if ($hugs > 20) {
$quote = $quotes[3];
}
if ($hugs > 50) {
$quote = $quotes[4];
}
if ($hugs > 100) {
$quote = $quotes[5];
}
if ($hugs > 150) {
$quote = $quotes[6];
}
if ($hugs > 200) {
$quote = $quotes[7];
}
if ($hugs > 250) {
$quote = $quotes[8];
}
if ($hugs > 500) {
$quote = $quotes[9];
}
if ($hugs > 750) {
$quote = $quotes[10];
}
if ($hugs > 1000) {
$quote = $quotes[11];
}
if ($hugs > 1500) {
$quote = $quotes[12];
}


As the intervals between the hug counts are irregular, is there a way to condense this down at all?

TIA.

Answer

You could certainly condense it! One way is to build an associative array (key-value pairings), like the example below.

/**
 * Returns a quote based on the number of hugs
 *
 * @param int $hugs
 * @param array $quotes
 *
 * @return string|null
 */
function getQuoteFromHugs($hugs, $quotes) {
    $hugs_quotes = array(
        1500 => $quotes[12],
        1000 => $quotes[11],
        750 => $quotes[10],
        500 => $quotes[9],
        250 => $quotes[8],
        200 => $quotes[7],
        150 => $quotes[6],
        100 => $quotes[5],
        50 => $quotes[4],
        20 => $quotes[3],
        10 => $quotes[2],
        5 => $quotes[1],
        0 => $quotes[0],
    );

    foreach($hugs_quotes as $hug_minimum => $quote) {
        if($hugs > $hug_minimum) {
            return $quote;
        }
    }
    return null;
}

// Usage
$quote = getQuoteFromHugs($hugs, $quotes);

This iterates through each key-value pairing in order and sees if your $hugs parameter is greater than the key. If so, it returns the value associated with that key.