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