user1265072
user1265072

Reputation: 13

Looking for a more elegant solution to huge if elseif block

The following php check a question number against a range and assigns a chapter of text based on the matching condition. I can't help but think there is a better, faster way to accomplish this.

$qnum = $questionArray[$key][questionNum];

if ($qnum <= 10){
    $chapterText = str_replace("full", "chapter1", $refTextBook);
}
elseif ($qnum > 10 && $qnum <= 20) {
    $chapterText = str_replace("full", "chapter2", $refTextBook);
}
elseif ($qnum > 20 && $qnum <= 30) {
    $chapterText = str_replace("full", "chapter3", $refTextBook);
}
elseif ($qnum > 30 && $qnum <= 40) {
    $chapterText = str_replace("full", "chapter4", $refTextBook);
}
elseif ($qnum > 40 && $qnum <= 50) {
    $chapterText = str_replace("full", "chapter5", $refTextBook);
}
elseif ($qnum > 50 && $qnum <= 60) {
    $chapterText = str_replace("full", "chapter6", $refTextBook);
}
elseif ($qnum > 60 && $qnum <= 70) {
    $chapterText = str_replace("full", "chapter7", $refTextBook);
}
elseif ($qnum > 70 && $qnum <= 80) {
    $chapterText = str_replace("full", "chapter8", $refTextBook);
}
elseif ($qnum > 80 && $qnum <= 90) {
    $chapterText = str_replace("full", "chapter9", $refTextBook);
}
elseif ($qnum > 90 && $qnum <= 100) {
    $chapterText = str_replace("full", "chapter10", $refTextBook);
}
elseif ($qnum > 100 && $qnum <= 110) {
    $chapterText = str_replace("full", "chapter11", $refTextBook);
}
elseif ($qnum > 110 && $qnum <= 120) {
    $chapterText = str_replace("full", "chapter12", $refTextBook);
}
elseif ($qnum > 120 && $qnum <= 130) {
    $chapterText = str_replace("full", "chapter13", $refTextBook);
}
elseif ($qnum > 130 && $qnum <= 140) {
    $chapterText = str_replace("full", "chapter14", $refTextBook);
}
elseif ($qnum > 140 && $qnum <= 150) {
    $chapterText = str_replace("full", "chapter15", $refTextBook);
}

Upvotes: 0

Views: 111

Answers (1)

Waleed Khan
Waleed Khan

Reputation: 11467

function getChapterName($qnum) {
    return "chapter".ceil($qnum / 10);
};

Upvotes: 7

Related Questions