Kayla Kayla - 2 years ago 81
PHP Question

Avoid multiple if statements in PHP (use array or some other option)

I am creating a conversion table using PHP and I have to check the user's input against A LOT of scenarios and I started by using if statements but this doesn't seem to be efficient whatsoever and I was hoping for an easier way to go through all the scenarios.

I looked into ternary and switch options but those don't seem to do what I need it to do and I also considered array's (the option I think I need to use)

What I'm trying to do:
The user enters in a grade level and scores for a category. Based on the sum of those scores and the grade level, I need to compare them to get two other scores
Example code:

if ($grade == 1 && $sumScore <= 5)
$textscore = 'Beginning';
if ($grade ==1 && ($sumScore>5 && $sumScore <=8))
$textScore = 'Intermediate';


There are 13 grades (K-12) and 4 categories I need to go through all with their own "raw scores" to consider to get these other scores. How can I avoid using a ton of If/Else if statements?


Answer Source

You could use a two-dimensional array that's 13x4. Then you can use a nested for loop to go through each possibility and just have one statement that gets run a bunch of times because of the for loops.

For example, the array might look like this:

$textscores = array (
  1 => array(5 => 'Beginning', 8 => 'Intermediate', ...),
  3 => array(5 => 'Intermediate', ...),

The nested for loop might look like this:

foreach($textscores as $grade => $scores) {
  foreach($scores as $sumScore => $textScore) {
    if($userGrade == $grade &&  $userSumScore <= $sumScore) {
      $userTextScore = $textScore;
      break 2;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download