Jump to content

Input Radio Button and Using Arrays


garfan

Recommended Posts

Hello,

 

I am fairly novice at PHP. I have a couple of reference books*, but they seem to be vague on the subject of "arrays", that is why I am asking for help today. I am trying to create a simple array using a form and radio button selectors. At the bottom I will explain what I am trying to accomplish.

 

Here is the sample of my code using one question:

 

HTML........................................................................................................................................................................................

 

<fieldset>
<legend>DO YOU EXERCISE DAILY?</legend>
<form action="" method="post" />

<label for="question" class="question">I often exercise on a daily basis for at least 20 minutes a day</label>
 
<label for "Never" class="radio">
<input type="radio" name="answer[0]=1" value="Never" />
Never</label>
 
<label for="Seldom" class="radio">
<input type="radio" name="answer[1]=2" value="Seldom" />
Seldom</label>
 

<label for="Occasionally" class="radio">
<input type="radio" name="answer[2]=3" value="Occasionally" />

Occasionally</label>
 
<label for="Often" class="radio">
<input type="radio" name="answer[3]=4" value="Often" />
Often</label>
 
<label for="Always" class="radio">
<input type="radio" name="answer[4]=5" value="Always" />

Always</label>
</form>

</fieldset>

 

When a question is asked, the user can choose only one (radio button) answer. That answer is assigned a number (1 thru 5) and will be displayed and then eventually tallied along with answers to other questions (not shown) for a grand total or sum.

 

PHP..........................................................................................................................................................................................

 

<?php

//Error Displaying
ini_set ('display_errors',1);
error_reporting (E_ALL & ~E_NOTICE);

 

//Print each answer

<?php
if (isset($_POST["answer"]) && is_array($_POST["answer"])
&& count($_POST["answer"]) > 0)
{
    foreach ($_POST["answer"] as $answer)
        {
            echo htmlspecialchars($answer, ENT_QUOTES);
            echo '<br />';
        }
}

?>

// Print each key and value.
<?php
$answer = array ('Never', 'Seldom', 'Occasionally', 'Often', 'Always');
foreach ($answer as $ans => $answer) {
    print "$ans: $answer<br />\n";
}
?>

 

 

I am able to get the answer (picked via radio button) to print or echo on the page, but I am not sure how to display a number represting each choice (1 for Never ~ 5 for Always). Not sure what I am doing wrong. I have researched other examples on the web and tried their logic, still no success. I guess I am just not getting it.

 

Any advice or help would be appreciated. Also do any of you readers recommend another book to learn from?

 

Signed,

Garfan

 

*Murachs PHP and MYSQL

*PHP For The World Wide Web by Larry Ullman

Link to comment
Share on other sites

Arrays are just there to make it easier to have multiple "values" in one form. In your case you can think of that as multiple answers to your questionnaire... however you only have one question, and that one question only has one answer. So actually arrays don't do you any good here. They'd be more suited if you wanted to do multiple questions.

 

<form action="" method="post" />
<label for="question" class="question">I often exercise on a daily basis for at least 20 minutes a day</label>
 
<label for="Never" class="radio">
<input type="radio" name="answer" value="Never" />
Never</label>
 
<label for="Seldom" class="radio">
<input type="radio" name="answer" value="Seldom" />
Seldom</label>
 
<label for="Occasionally" class="radio">
<input type="radio" name="answer" value="Occasionally" />
Occasionally</label>
 
<label for="Often" class="radio">
<input type="radio" name="answer" value="Often" />
Often</label>
 
<label for="Always" class="radio">
<input type="radio" name="answer" value="Always" />
Always</label>
</form>
if (isset($_POST["answer"]))
{
    echo htmlspecialchars($_POST["answer"], ENT_QUOTES);
}
So for the purposes of showing how arrays work, let's say you wanted multiple questions at a time.

 

Each "value" from the form will be an answer to each question. Like how arrays normally work in PHP, you want the key to identify what the value corresponds to. Here, the key makes most sense to identify the question: 0 for the first question, 1 for the second, and so on. If you were getting these questions from a database then using the question ID would be better than just counting from zero.

 

"But doesn't that mean each answer for a question has the same name?" Yes. Yes it does. But a user can only choose one answer per question so that's fine. It also works perfectly with how radio buttons work in HTML: only one value can be chosen for each unique name. That's why you don't have to write anything that automatically unselects previous values when a user selects a new one... and if you played around with your form you would have noticed that didn't happen (because all the names were different).

I often exercise on a daily basis for at least 20 minutes a day

<label for="Never" class="radio">
<input type="radio" name="answer[0]" value="Never" />
Never</label>

<label for="Seldom" class="radio">
<input type="radio" name="answer[0]" value="Seldom" />
Seldom</label>
 
<label for="Occasionally" class="radio">
<input type="radio" name="answer[0]" value="Occasionally" />
Occasionally</label>
 
<label for="Often" class="radio">
<input type="radio" name="answer[0]" value="Often" />
Often</label>
 
<label for="Always" class="radio">
<input type="radio" name="answer[0]" value="Always" />
Always</label>

<hr />

I like eating fatty and fried foods because they are so damn delicious.

<label for="Never" class="radio">
<input type="radio" name="answer[1]" value="Never" />
Never</label>

<label for="Seldom" class="radio">
<input type="radio" name="answer[1]" value="Seldom" />
Seldom</label>
 
<label for="Occasionally" class="radio">
<input type="radio" name="answer[1]" value="Occasionally" />
Occasionally</label>
 
<label for="Often" class="radio">
<input type="radio" name="answer[1]" value="Often" />
Often</label>
 
<label for="Always" class="radio">
<input type="radio" name="answer[1]" value="Always" />
Always</label>
I also removed the label on the question because it's not really appropriate there: labels match up text and input, and there is no one input to match up with the question text (rather, there's too many). There are more appropriate things to use but that's for another time.

 

Now, $_POST["answer"] will be the array you're expecting. Print it out to see what you got.

if (isset($_POST["answer"]) && is_array($_POST["answer"])
&& count($_POST["answer"]) > 0)
{
    print_r($_POST["answer"]);
}
Edited by requinix
Link to comment
Share on other sites

Requinix,

 

Thank you so much for clarifying. I did have more code I could have submitted with other questions to follow, but I did not want it to be long winded.

Is there a way to assign a number to each choice? Meaning after a user selects an answer, lets say Always is selected and assigned a 5, after hitting the submit button it would display that number on the page.

 

Thanks again in advance.

Garfan.

Link to comment
Share on other sites

Barand,

 

Thank you so much for the help. It worked.

 

One final question pertaining to this post.

How would one add the results, in other words get a sum of all the values? I will have multiple questions that will be assigned a number (1 ~ 5) based off their answer. I looked in PHP.net it suggested using array_sum().

 

Here is their example:

<?php
$a 
= array(2468);
echo 
"sum(a) = " array_sum($a) . "\n";

 

Is that the best way to achieve the result?

 

Garfan.

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.