1

I have an rather simple php code which I would like to change into an loop (if possible). Otherwise the code will be too long at the end. Unfortunately I am not really familiar with php (the code is for an Online questionaire).

if (value('X001_03') == 1) {  
    question('VAR', array(1));
} elseif(value('X001_03') == 2) {
    question('VAR', array(1,2));
} elseif(value('X001_03') == 3) {
    question('VAR', array(1,2,3));
} elseif(value('X001_03') == 4) {
    question('VAR', array(1,2,3,4));
} elseif(value('X001_03') == 5) {
    question('VAR', array(1,2,3,4,5));
} elseif(value('X001_03') == 6) {
    question('VAR', array(1,2,3,4,5,6));
} elseif(value('X001_03') == 7) {
    question('VAR', array(1,2,3,4,5,6,7));
} elseif(value('X001_03') == 8) {
    question('VAR', array(1,2,3,4,5,6,7,8))
}

Basically the number after == has to increment by "1" until it reaches 9, while the range of the arrays increases at the same time.

Thankful for any help!

Best regards

1
  • 1
    range() might help... Commented Jan 31, 2019 at 11:04

1 Answer 1

12

Should not need a loop, you should be able to replace the whole thing with just

question('VAR', range(1, value('X001_03')));

range(x, y) allows you to create an array containing values from x to y.

Sign up to request clarification or add additional context in comments.

7 Comments

thank you for your fast answer! Do I understand it correctly that I still would have to write one line for every if condition? Like: question('VAR', range(1, value('X001_03'))); question('VAR', range(2, value('X001_03'))); and so on?
no. This single line replace all your if{}elseif()... structure.
No, this replaces the code you had shown completely. range(1,1) gets you the equivalent of array(1), range(1,2) gets you the equivalent of array(1, 2), and so on - so this makes any loops completely superfluous at this point.
okay, nice! But with that i still get an error here: question('VAR', range(1,9, value('X001_01'))); Sorry, probably a stupid question, but as I mention- I am pretty much a beginner with php.
range takes two parameters, not three. You probably meant range(1, value('X001_01')) in that place?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.