How to display a form answer if it matches the answer in an array in php -
i've been trying learn php , practice, made array of family guy characters based off last name. tried asking question in form , wanted code check array see if matches correct answer in array. i'm still new php, learning experience. code looks this...
<?php $families = array( "griffin" => array( "peter", "louis", "chris", "stewie", "meg" ), "quagmire" => array( "glen" ), "brown" => array( "cleveland", "loretta", "junior" ) ); ?> <html> <head> </head> <body> of these family guy characters part of griffin family? <form action = "familyguyquestions.php" method = 'post'> a: <input type = "radio" name = "cleveland">cleveland b: <input type = "radio" name = "glenn">glenn c: <input type = "radio" name = "meg">meg d: <input type = "radio" name = "quagmire">quagmire <input type = "submit" name = "submitquestion"> </form> </body> </html>
there 2 ways of doing this:
- send form php, check answer , render page displaying whether answer or not
- make ajax request server , return json containing whether answer correct or not , update dom
as how send data, should have same name
attribute on radio buttons , hidden input know array , array key (since have array of arrays).
html:
<html> <head> </head> <body> of these family guy characters part of griffin family? <form action = "familyguyquestions.php" method = 'post'> <input type="hidden" value="families" name="what_array" /> <input type="hidden" value="griffin" name="what_array_key" /> a: <input type = "radio" name="answer" value = "cleveland">cleveland b: <input type = "radio" name="answer" value = "glenn">glenn c: <input type = "radio" name="answer" value = "meg">meg d: <input type = "radio" name="answer" value = "quagmire">quagmire <input type = "submit" name = "submitquestion"> </form> </body> </html>
php:
if (false == isset($_post['what_array'])) { // no array here, return error } if (false == isset($_post['what_array_key'])) { // no key here, return error } if (false == isset($_post['answer'])) { // no answer, return error } $the_array = $_post['what_array']; $the_array_key = $_post['what_array_key']; $the_answer = $_post['answer']; $the_array = ($$the_array); if (false == isset($the_array)) { // array set, return error } if (true == in_array($the_answer, $the_array[$the_array_key])) { // here answer ok } else { // wrong answer }
notice double dollar sign on $$the_array
. how variable string. if $the_array
'families', $$the_array
actual array in want look.
Comments
Post a Comment