Imalea Imalea - 12 days ago 6
PHP Question

Best way to store phrases for an algorithm

Building a simple algorithm where, based on various inputs (x, y, z), a phrase will be sent back to the user. What's the fastest / smartest way to store and search for these phrases?

Currently, I'm using various if statements. But I'm wondering if I should instead use some sort of dictionary, or hash maps.

I've posted a code sample here.

Thank you!

for ( $i=0 ; $i < count($age) ; $i++ ) {
if ($age[$i] >= 95) {
$something = "You need a plant";
} elseif ($age[$i] >= 85 && $age[$i] < 95) {
$something = "You need a small rug and a plant";
} elseif ($age[$i] >= 75 && $age[$i] < 85) {
$something = "You need a rug";
} elseif ($age[$i] >= 60 && $age[$i] < 75) {
$something = "You need a coffee table";
} elseif ($age[$i] >= 55 && $age[$i] < 60) {
$something = "You need a small table";
} elseif ($age[$i] >= 51 && $age[$i] < 55) {
$something = "You need a table";
} elseif ($age[$i] >= 42 && $age[$i] < 51) {
$something = "You need a knife";
} elseif ($age[$i] >= 35 && $age[$i] < 42) {
$something = "You need a knife and a jar";
} elseif ($age[$i] >= 22 && $age[$i] < 35) {
$something = "You need a knife, bowl, jar and a small book";
} elseif ($age[$i] >= 5 && $age[$i] < 22) {
$something = "You need a knife, bowl, jar and a book";
} else {
$something = "Go back to sleep";
}

if ($somethingElse[$i] >= 30) {
$also = " and we'll see you tomorrow!";
} else {
$also = ".";
}

$phrase[$i] = ''.$something.''.$also.'';
}

Answer

For the first part of the phrase, you could use an array with the age limits as keys and the texts as values. For the second part, which is more of a yes/no choice, you can use a ternary operator.

foreach is also nicer for looping over the $age array:

$phrases = [
    95 => "You need a plant",
    85 => "You need a small rug and a plant",
    75 => "You need a rug",
    65 => "You need a coffee table",
    55 => "You need a small table",
    51 => "You need a table",
    42 => "You need a knife",
    35 => "You need a knife and a jar",
    22 => "You need a knife, bowl, jar and a small book",
    5  => "You need a knife, bowl, jar and a book",
];

foreach ($age as $i => $a) {
    foreach ($phrases as $limit => $something) {
        if ($a >= $limit) break;
    }
    $also = $somethingElse[$i] >= 30 ? " and we'll see you tomorrow!" : ".";
    $phrase[] = "$something$also";
}   

Note that unless you already had an array $phrase, you don't need to specify the index $i, as [] will just make it append at the end. So in the end you only need $i for $somethingElse. The reason why it is still needed in the foreach syntax.