Practical one...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
al3xandar
Forum Newbie
Posts: 15
Joined: Tue Dec 16, 2008 3:05 pm

Practical one...

Post by al3xandar »

Recently I started writing a questionnaire, and I need help with calculating values. I've managed to put item names in MySQL database and retrieve them in a table. Questionnaire consists of 200 yes/no questions, so I did something like this:
for($i = 1; $i <= 200; $i++) {
$row = mysql_fetch_array($result);
extract($row);
echo $item;
echo "<input type = 'radio' name = 'rsp$i' value = 'y'>yes";
echo "<input type = 'radio' name = 'rsp$i' value = 'n'>no";
echo "<br>";
}
I hope you've got the picture... "y" values are positive responses, and "n" negative ones (surprisingly). I would like to count "y"'s for questions e.g. #1,#5,#6,#9,#15, and to add value "1" for every "y" found on those variables. Then I would like to create new variable, let's call it $var, which would have value 5 if respondent answered "yes" to all five questions.
I reckon this is trivial stuff, but, hey, I'm still official beginner...

Thanx in advance!!
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Practical one...

Post by requinix »

Instead of y/n use 1/0. Then just add them together:

Code: Select all

$var = $_POST["rsp1"] + $_POST["rsp5"] + $_POST["rsp6"] + $_POST["rsp9"] + $_POST["rsp15"];
If you made an array out of the form inputs then you could probably make a few things easier.

Code: Select all

echo "<input type = 'radio' name = 'rsp[$i]' value = '1'>yes";
echo "<input type = 'radio' name = 'rsp[$i]' value = '0'>no";

Code: Select all

function rsp() {
    $array = func_get_args();
    foreach ($array as $key => $value) $array[$key] = $_POST["rsp"][$value];
    return $array;
}
 
$var = array_sum(rsp(1, 5, 6, 9, 15));
al3xandar
Forum Newbie
Posts: 15
Joined: Tue Dec 16, 2008 3:05 pm

Re: Practical one...

Post by al3xandar »

Well, I want to create another variable which will count no's... :D

So that 0-1 coding thing is just not doing any good! That's the problem!
:?
terminator24h
Forum Newbie
Posts: 4
Joined: Mon Mar 02, 2009 11:43 pm

Re: Practical one...

Post by terminator24h »

If the only possible responses are yes and no, you could count "no"s by simply subtracting "yes"s from the total number of questions.
Post Reply