Matt Cowley
Matt Cowley

Reputation: 2373

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.

Upvotes: 2

Views: 65

Answers (3)

Chris Forrence
Chris Forrence

Reputation: 10094

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.

Upvotes: 3

André Laszlo
André Laszlo

Reputation: 15537

What about something like this:

$steps = array(0, 5, 10, 20, 50, 100, 150, 200, 250, 500, 750, 1000, 1500);
foreach ($steps as $index => $step) {
    if ($hugs > $step) {
        $quote = $quotes[$index];
    }
}

This uses the $steps array to map the index in the $quotes array to the next step.

Upvotes: 2

Fabricator
Fabricator

Reputation: 12772

Here's a way to organize it:

function getQuote($hugs) {
    $hugQuotes = array(
        array(1500, $quotes[12]),
        array(1000, $quotes[11]),
        ...
    );

    foreach($hugQuotes as $v) {
        $c = $v[0];
        $quote = $v[1];
        if ($hugs > $c) return $quote;
    }

    return $quote;
}

Upvotes: 1

Related Questions