Jump to content

or vs if else


davidcriniti

Recommended Posts

Hi,

 

I've made an online test for my kids at school, which is marked automatically via php.

 

Most questions have been ok, using this sort of format:

if ($q001 == "right") {$q001score = 1;}else {$q001score = 0;};

 

However, I've had a bit of trouble with questions where there is more than one answer.

 

I've tried using 'or' with little success. I find that '1' gets added to the score regardless of whether I get the right answer, wrong answer, or input no answer when using the following script:

 

if ($q001 == "right" or "right2") {$q001score = 1;}else {$q001score = 0;};

 

I've also substituted || for 'or' with no success.

 

 

I have solved the problem by extending the if-else statement as follows:

if ($q001 == "right" ) {$q001score = 1;} else if ($q001 == "right2") {$q001score = 1;}else {$q001score = 0;};

 

I was just wondering if I could reduce the amount of code by altering the 'or' statement above as the if, else if, else statement seems a bit cumbersome?

 

 

Yours gratefully,

 

Dave

 

 

 

 

 

 

Link to comment
Share on other sites

The OR and || operators are both correct. You are not following the statement though, Consider this correction:

$q001 == "right" || $q001 == "right2"

 

You can only use another statement, You cannot use "This or that", it has to be "if this = this OR this = that"

 

If you wish for a more "automated" method, you can define an array.

 

$correct_answers = Array('right', 'right2');
if (in_array($q001, $correct_answers)) {
   $q001score = 1;
} else {
   $q001score = 0;
}

 

This will save you from typing a pile of IF/AND/OR statements provided you add to the array.

 

EDIT: Updated another method.

Link to comment
Share on other sites

Just to note that:

 

$q001 == "right" or "right2"

 

works but is not the desired result as this always executes ($q001score = 1) never ($q001score = 0) because "right2" equals to true and because of the nature-of (or, ||) statement (which executes the if-body whenever a, b or both are true)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.