ok ok .. a hash... tomhath is exactly right...
i was playing with your stuff so pardon me if i explain a little also
simple:
$arr = array();
$arr[0] = 'value for 0';
$arr[1] = 'value for 1';
$arr[2] = 'value for 2';
$hash = array();
$hash['key 1'] = 'value for key 1';
$hash['key 2'] = 'value for key 2';
$hash['key 3'] = 'value for key 3';
complex:
as tomhath says: a hash is just called an associative array, you can use the terms interchangably in php
in an array you need to know the index of the item 0...n
this is often meaninless to your data... and since it is meaningless you most often need to start at the beginning and check every single item in your array to find the one you are looking for
$found_at = NULL;
for( $i=0; $i<count($arr); $i++ ) {
if ( $arr[$i] = $value_we_are_looking_for ) {
$found_at = $i;
}
}
a hash assignes a unique identifier to each item in the array, which is often more meaningfull, and since you know the exact meaning you can more easilly access it directly... this identifier can be a string or something other than an integer...
for you this means saying
so now you can ask this it replace the loop above:
$correct_answers['what is my favorite color?'] = 'my answer';
if ( $users_answer == $correct_answers[$question_asked] ) {
// they were right
}
You didn't even ask me this but JUST FOR FUN:
if you are up in middle of the night and can't sleep like me... try this, it was a fun game:
in this format you have to pull out multiple rows for each question, so you will have to do a pass after you pull your query to group them into something usefull in php (but you can just use a hash for that):
here is all the stuff i created to play with your code
CREATE TABLE `questions`
(
`question_id` tinyint(4) NOT NULL auto_increment,
`category_id` tinyint(4) NOT NULL default '0',
`question_text` varchar(200) NOT NULL default '',
`correct_answer_id` tinyint(4) NOT NULL default '0',
PRIMARY KEY (`question_id`),
FULLTEXT KEY `question_text` (`question_text`)
) TYPE=MyISAM;
CREATE TABLE `answers`
(
`answer_id` tinyint(4) NOT NULL auto_increment,
`question_id` tinyint(4) NOT NULL default '0',
`answer_text` varchar(200) NOT NULL default '',
PRIMARY KEY (`answer_id`)
) TYPE=MyISAM;
INSERT INTO `questions`
(`question_id`, `category_id`, `question_text`, `correct_answer_id`)
VALUES
(1, 0, 'what is your favorite color', 1),
(2, 0, 'what is your favorite language', 8);
INSERT INTO `answers`
(`answer_id`, `question_id`, `answer_text`)
VALUES
(1, 1, 'red'),
(2, 1, 'blue'),
(3, 1, 'pink'),
(4, 2, 'php'),
(5, 2, 'python'),
(6, 2, 'ruby'),
(7, 2, 'smalltalk'),
(8, 2, 'java'),
(9, 2, 'prolog'),
(10, 2, 'lisp');
<?php
/// connect to database
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "test";
mysql_connect($db_host, $db_username, $db_password);
mysql_select_db($db_dbname);
/// the left join assures that we find questions that do not have any answers logged
$result = mysql_query("
SELECT
Q.question_id,
Q.category_id,
Q.question_text,
Q.correct_answer_id,
A.answer_id,
A.answer_text
FROM
questions as Q,
answers as A
WHERE
Q.question_id = A.question_id
");
/// compose assiciated array (hash) out of our results from our database query
$questions = array();
while ( $row = mysql_fetch_array($result) )
{
if ( !isset($questions[$row['question_id']]) ) {
$questions[$row['question_id']] = array(
'question_id' => $row['question_id'],
'category_id' => $row['category_id'],
'question_text' => $row['question_text'],
'correct_answer_id' => $row['correct_answer_id'],
'answers' => array()
);
}
if ( $row['answer_id']!==NULL ) {
$questions[$row['question_id']]['answers'][$row['answer_id']] = array(
'answer_id' => $row['answer_id'],
'answer_text' => $row['answer_text']
);
}
}
/// pose questions
print <<<END
<form action="{$_SERVER['PHP_SELF']}" method="post">\n
END;
foreach ( $questions as $question ) {
print <<<END
<fieldset style="width: 400px;">
<legend>Question {$question['question_id']}</legend>
<big><b>Q: {$question['question_text']}?</b></big>
<br>
<small>(correct answer choosen by default)</small><br>
<br>\n
END;
/// put the items in random order
knuthShuffle($question['answers']);
/// step through our shuffled items
foreach ( $question['answers'] as $answer ) {
$choosen = ($question['correct_answer_id']==$answer['answer_id']) ? ' checked="checked"' : '' ;
print <<<END
<input type="radio" name="answers[{$question['question_id']}]" value="{$answer['answer_id']}"$choosen>{$answer['answer_text']}<br>\n
END;
}
print <<<END
</fieldset><br>\n
END;
}
print <<<END
<input type="submit" value="Submit Answers">
</form>\n
END;
/// show answers
if ( isset($_POST['answers']) ) {
foreach ( $_POST['answers'] as $question_id=>$answer_id ) {
$correctness = ($answer_id==$questions[$question_id]['correct_answer_id']) ? '<font color="green">CORRECT</font>' : '<font color="red">INCORRECT</font>';
print <<<END
<fieldset style="width: 400px;">
<legend>Answer to Question {$question_id}</legend>
<big><b>Q: {$questions[$question_id]['question_text']}?</b></big>
<br><br>\n
You Answered : <b>{$questions[$question_id]['answers'][$answer_id]['answer_text']}</b>
<br>
Your Answer is : <b>{$correctness}</b>
</fieldset><br>\n
END;
}
}
/// php shuffle() and any rand() based functions are worthless, so lets write our own, or rather Knuth's
/// yeah yeah its not perfect, but its linear... and we're not running an online casino
function knuthShuffle( &$array, $number_of_shuffles=1 )
{
/// only need to calculate once
$max = count($array)-1;
/// need to use this, algorithm deals in integer array indexes and we might have an associative array
$keys = array_keys($array);
while($number_of_shuffles>0) {
for ( $i=$max; $i>0; $i-- ) {
$j = mt_rand(0,$i);
$swap = $array[$keys[$j]];
$array[$keys[$j]] = $array[$keys[$i]];
$array[$keys[$i]] = $swap;
}
$number_of_shuffles--;
}
}
?>