-1

So I have a bunch of questions with radio buttons, each question having three options to choose from. I have a bunch of If statements ( a lot of them) that determine a final answer based on answers to each question.

For example:

Question 1 : 
           a)
           b)
           c)

Question 2 : 
           d)
           e)
           f)

Question 3 : 
           g)
           h)
           i)

and so on.

if statements will be as follows : if ( Question 1 == a || Question 2 == f && Question 3 == i )

If I want to get all the conditions as form of if statements, it'd take too much space and probably not the best practice.

What is the best way to refactor all these if statements?

tyrell_c
  • 503
  • 3
  • 10
  • 24
  • 2
    That very much depends on what the logic is for arriving at the final answer. We don't know that... – deceze Jul 27 '15 at 12:59
  • 2
    In the abstract, there is no "best" way. The best solution will depend markedly on how the choices interrelate with one another, what the data they're referring to is, etc. It might be nested `if`s, it might be map lookups, it might be aggregating information, ... – T.J. Crowder Jul 27 '15 at 12:59
  • I would recommend using [state machine](https://www.google.ca/search?q=state+machine&oq=state+machine&aqs=chrome..69i57.2047j0j1&sourceid=chrome&es_sm=93&ie=UTF-8) – ndd Jul 27 '15 at 13:01
  • possible duplicate of [Alternative to a million IF statements](http://stackoverflow.com/q/10029089/1048572) – Bergi Jul 27 '15 at 13:05

2 Answers2

0

If every single combination of choices leads to a unique outcome, you're actually looking at an n-dimensional matrix. In simpler words, think of every option as a step in the path in an array:

$outcomes = array(
    'a' => array(
        'd' => array(
            'g' => 'Outcome 1',
            'h' => 'Outcome 2',
            'i' => 'Outcome 3'
        ),
        'e' => array(..),
        ..
    'b' => array(..),
    ..
);

echo 'The outcome is: ', $outcomes[$question1][$question2][$question3];

Whether this is actually the best possible way to implement this is questionable, we don't know without knowing more about your logic.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

I ended up refactoring it with switch statements and functions. I'm sure there are more elegant ways I could do it. Will update answer if I found a way.

tyrell_c
  • 503
  • 3
  • 10
  • 24