Author Topic: Questions Array not shuffling  (Read 1496 times)

0 Members and 1 Guest are viewing this topic.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Questions Array not shuffling
« on: March 16, 2010, 08:54:24 AM »
I am making this quiz following a tutorial I got online. it works by having the correct answer as the first part of the array then has a code to shuffle them other wise every time the correct answer will be the first one you can select. I have applied the code and done everything as it says but it isnt shuffling. Every time the correct answer appears first.

Here is the questions and answers array and the code to shuffle it. Can any one give me a hand and help me get it to work?

The questions and answers
<?php 
$questions 
= array('FTP','AJAX','RSS','XSS','PHP','W3C','XML','YUI','HTML','CGI','SSL','SQL','HTTP','CSS','SOAP','WAI','SSI','JSON','XSLT','WCAG'); 
$answers = array( 
array(
=>'File Transfer Protocol','Force Through Privately','File Through Protocol','File Test Protocol'), 
array(
=> 'Asynchronous JavaScript and XML','All JavaScript and XML','Alternative Java and XML','Actual JavaScript and XML'), 
array(
=> 'Really Simple Syndication','Really Simple Scripting','Ready-Styled Scripting','Really Stupid Syndication'), 
array(
=> 'Cross-site Scripting','Cross-site Security','Cleverly Structured Scripting','eXtremely Safe and Secure'), 
array(
=> 'PHP: Hypertext Preprocessor','Post Hypertext Processor','Practical HTML Processing','Process HTML Prettily'), 
array(
=> 'World Wide Web Consortium','World Wide Web Committee','World Wide Web Creatives','Wakefield Willy Wavers Club'), 
array(
=> 'eXtensible Markup Language','eXtendable Markup Language','Crossover Markup Language','eXtreme Markup Language'), 
array(
=> 'Yahoo User Interface','Yahoo\'s Useful Idea','Yahoo Utility Interface','Yahoo User Interaction'), 
array(
=> 'Hypertext Markup Language','Human Markup Language','Helpful Markup Language','Hypertext Memory Language'), 
array(
=> 'Common Gateway Interface','Common or Garden Interaction','Computer\'s Graphical Intelligence','Common Graphical Interface'), 
array(
=> 'Secure Sockets Layer','Server Security Layer','Server Security Level','Secret Socket Layer'), 
array(
=> 'Structured Query Language','Stupid Query Language','Secure Query Language','Strict Query Language'), 
array(
=> 'Hypertext Transfer Protocol','Hypertext Traffic Protocol','HTML Traffic Transfer Protocol','HTML Through Traffic Protocol'), 
array(
=> 'Cascading Style Sheets','Custom Style Sheets','Clientside Style Sheets','Calculated Style Sheets'), 
array(
=> 'Simple Object Access Protocol','Structured Object Access Protocol','Simple, Objective And Private','Simply Obvious Access Principle'), 
array(
=> 'Web Accessibility Initiative','World Wide Accessibility Intiative','World Wide Accessibility Incorporation','Web Accessibility and Inclusion'), 
array(
=> 'Server-Side Include','Server-Side Intelligence','Scripted Server Include','Secure Server Include'), 
array(
=> 'JavaScript Object Notation','JQuery-Scripting Object Notation','Just Simple Object Notation','JavaScript Over the Net'), 
array(
=> 'eXtensible Stylesheet Language Transformation','eXpandable Stylesheet Language Transfer','eXtensible Stylesheet Language Transfer','eXtendable Stylesheet Language Transformation'), 
array(
=> 'Web Content Accessibility Guidelines','Wakefield Community Action Group','Web Criteria And Guidelines','World-wide Common Access Group'
); 
?>


function shuffle_assoc(&$array) { 
    
$keys array_rand($arraycount($array)); 
    foreach(
$keys as $key
        
$new[$key] = $array[$key]; 
        
$array $new
        return 
true
    } 


Also there was this. I dont know if it related.
<?php 
$pattern 
' '
$replace '_'
shuffle_assoc($answers[$num]); 
foreach (
$answers[$num] as $answer) { 
    
$answer2 str_replace($pattern,$replace,$answer); 
    echo 
"<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n"
    echo 
"<label for=\"$answer2\">$answer</label></li>\n"

?>


Any help anyone could give me would be amazing. Thanks!


Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #1 on: March 16, 2010, 01:53:44 PM »
Can anyone help at all I am really desperate

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #2 on: March 16, 2010, 02:00:15 PM »
I just copies all of the code you just posted and set $num to one of the values in the arrays and it works fine for me. Every time I refresh the page the answers are in a different order.

Although that is a pretty poor implementation, IMHO.
« Last Edit: March 16, 2010, 02:03:25 PM by mjdamato »
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline hcdarkmage

  • Enthusiast
  • Posts: 326
  • Gender: Male
  • I.U.I.Y.G., E.Y.C.B.
    • View Profile
Re: Questions Array not shuffling
« Reply #3 on: March 16, 2010, 02:04:42 PM »
I am making this quiz following a tutorial I got online. it works by having the correct answer as the first part of the array then has a code to shuffle them other wise every time the correct answer will be the first one you can select. I have applied the code and done everything as it says but it isnt shuffling. Every time the correct answer appears first.

Here is the questions and answers array and the code to shuffle it. Can any one give me a hand and help me get it to work?
I think your problem is in the answers array.

<?php 
$questions 
= array('FTP','AJAX','RSS','XSS','PHP','W3C','XML','YUI','HTML','CGI','SSL','SQL','HTTP','CSS','SOAP','WAI','SSI','JSON','XSLT','WCAG'); 
$answers = array( 
array(
=>'File Transfer Protocol','Force Through Privately','File Through Protocol','File Test Protocol'),  // <--- This belongs to array "0"
array(=> 'Asynchronous JavaScript and XML','All JavaScript and XML','Alternative Java and XML','Actual JavaScript and XML'),  // <--- This belongs to array "1"
array(=> 'Really Simple Syndication','Really Simple Scripting','Ready-Styled Scripting','Really Stupid Syndication'),  // <--- This belongs to array "2", etc.

?>

Change the zeros to correspond with the question array number.

Try that, see if it helps.
Stupid fat fiungers.
01000101-01101100-00100000-01000011-01100001-01110010-01100100-01101111-

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #4 on: March 16, 2010, 02:10:04 PM »
I think your problem is in the answers array.

Change the zeros to correspond with the question array number.

Try that, see if it helps.

No, that is not the problem. The 0 is to set the index of the first question value to 0 (which is unnecessary). The questions and answers are indirectly "associated" via the parent array IDs. Which is one reason that is a poor implementation. The code he posted works as long as you set $num to the value of one of the available indexes.

It is also a poor implementation because the code is using a custom function to randomize the answers instead of just using shuffle. The custom function is maintaining the index association, but it is not even used in the output so it is unnecessay overhead.
« Last Edit: March 16, 2010, 02:13:16 PM by mjdamato »
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #5 on: March 16, 2010, 02:16:43 PM »
Wouldnt it be smarter to do something like...

array('FTP' => array('File Transer Protocol', 'Force Yada Yada', 'Other Answer Here', 'W T F'));
array('PHP' => array('Blah Blah Blah', 'Blah blah blah', 'Foo Bar', 'Whatever'));

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #6 on: March 16, 2010, 02:19:31 PM »
Sorry I am really terrible at PHP what do you mean when you say you set one of the values to $num?

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #7 on: March 16, 2010, 02:31:58 PM »
Please. for the love of god and all that is holy. dont do it that way.... here
Code: [Select]
<?php
$questions 
= array('FTP' => 
array('File Transfer Protocol',
  'Force Through Privately',
  'File Through Protocol',
  'File Test Protocol'), 
    'Ajax' =>
array('Asynchronous JavaScript and XML',
  'All JavaScript and XML',
  'Alternative Java and XML',
  'Actual JavaScript and XML'));
foreach(
$questions as $q => $a) {
echo "What does " $q " stand for?<br />";
for($i=0$i<=4$i++) {
echo $a[$i] . "<br />";
}
}
?>

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #8 on: March 16, 2010, 02:45:07 PM »
Right now my test is all linked up with a leaderboard and results systems. It wouldnt effect it to much changing it like that would it?

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #9 on: March 16, 2010, 02:55:47 PM »
All that does is format the questions. unless your leaderboard is something extravagant like keeping track of the answers each person picked, it wont affect anything.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #10 on: March 16, 2010, 03:01:48 PM »
Before I go changing things I set one of the values to $num and nothing happened. I got all this code from a tutorial and it worked in the example there but as soon as download the source files and use it doesnt work.

When you said change the values you meant change the zero here to $num right.
array(=>'File Transfer Protocol','Force Through Privately','File Through Protocol','File Test Protocol'),  // <--- This belongs to array "0"


Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #11 on: March 16, 2010, 03:06:49 PM »
Did you copy the code EXACTLY? if so, that comment is idiotically incorrect, and therefore I would not trust this tutorial as far as I can throw it.

In your example, 0 is the key of the first value. Not the "array", whatever the hell that means.

$array = array(0 => 'answer1', 'answer2', 'answer3')

$array[0] = answer1
$array[1] = answer2
$array[2] = answer3

Now look at it this way:

$array = array('apples' => 'answer1', 'answer2, 'answer3')

$array[apples] = answer1
$array[1] = answer2
$array[2] = answer 3


Does that help you understand how the key => value relationship works? You can also check PHP documentation to get some ideas of this too. If no key is assigned, the array will assume it is the next logical progression of numbers, starting at 0.

Offline hcdarkmage

  • Enthusiast
  • Posts: 326
  • Gender: Male
  • I.U.I.Y.G., E.Y.C.B.
    • View Profile
Re: Questions Array not shuffling
« Reply #12 on: March 16, 2010, 03:12:04 PM »
Did you copy the code EXACTLY? if so, that comment is idiotically incorrect, and therefore I would not trust this tutorial as far as I can throw it.

Actually, that comment was my fault. It had nothing to do with what was originally posted, it was me mistaking my words. As mjdamato pointed out, I was looking at the problem the wrong way and got myself confused. Ignore the comments that where put in the code.

Oh, and thanks for calling me an idiot! It helps remind me that I'm human, lol.
« Last Edit: March 16, 2010, 03:12:57 PM by hcdarkmage »
Stupid fat fiungers.
01000101-01101100-00100000-01000011-01100001-01110010-01100100-01101111-

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #13 on: March 16, 2010, 03:12:46 PM »
I didnt just copy the code. He provided all the source files for it. He even had a working example on his site that shuffled them all about. I think I get it some more. I am terrible at PHP though.

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #14 on: March 16, 2010, 03:18:05 PM »
Well reaching out to the community is good with PHP, as that is what makes PHP great. Once you get good, give back. keeps the world of PHP going round and round.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #15 on: March 16, 2010, 03:24:49 PM »
I really dont know why the shuffle works for others and not me. Could some of the other code be effecting it?

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #16 on: March 16, 2010, 03:28:47 PM »
what is your result? what is your expected result?

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #17 on: March 16, 2010, 03:57:16 PM »
What do you mean?

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #18 on: March 16, 2010, 03:58:24 PM »
you said it isnt working for you, and its working for others. So what are you seeing when you run the script. i.e. what does it produce. And what are you seeing when you run the other peoples script.

This is what I mean by your result vs the others results.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #19 on: March 16, 2010, 04:49:02 PM »
For me when i run it, all the correct answers to the questions are just the first one.

as in it will be

question
correct answer
wrong answer
wrong answer
wrong answer

the correct answer is always answer 1 which makes it a bit easy. When I try the example all the answers are shuffled and above mjdamato said that it worked fine for him.

Offline ksugihara

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #20 on: March 16, 2010, 04:53:33 PM »
well, its tough to say from here what they are doing... have you looked into any of PHP's array shuffling functions? you could implement it yourself?

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #21 on: March 16, 2010, 06:19:00 PM »
I am really new....and really bad at php. I could find code and things but knowing where to put it and what to do with it is a huge problem for me.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #22 on: March 17, 2010, 09:00:38 AM »
Could it be a problem with the web server I am using or anything? The version of PHP it is running or anything. it seems weird I am just having this one problem

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #23 on: March 17, 2010, 11:46:19 AM »
Could it be a problem with the web server I am using or anything? The version of PHP it is running or anything. it seems weird I am just having this one problem

No, it is not a web server problem. The problem has to be that you are doing something outside of the code you posted previously. As I stated, I took the three blocks of code you posted in the initial message and ran it successfully. The only thing I had to do was set a value for $num to specify which question/answers I wanted displayed. To be honest, the code you are using is pretty crappy which has made me reluctant to try and fix your problem.

However, the only thing I can think of which would cause your problem would be if you run this line with one value for $num
shuffle_assoc($answers[$num]); 

And then run this with a different value for $num
foreach ($answers[$num] as $answer) { 
    
$answer2 str_replace($pattern,$replace,$answer); 
    echo 
"<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n"
    echo 
"<label for=\"$answer2\">$answer</label></li>\n"



Since you never showed how you are setting $num, I can't really do more than guess.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #24 on: March 17, 2010, 12:15:49 PM »
http://www.elanman.co.uk/2009/03/make-your-own-php-quiz-part-1/

This was the tutorial I was using, with all the code. Even his example that is pretty much identical to mine just works.

Offline hcdarkmage

  • Enthusiast
  • Posts: 326
  • Gender: Male
  • I.U.I.Y.G., E.Y.C.B.
    • View Profile
Re: Questions Array not shuffling
« Reply #25 on: March 17, 2010, 12:25:54 PM »
http://www.elanman.co.uk/2009/03/make-your-own-php-quiz-part-1/

This was the tutorial I was using, with all the code. Even his example that is pretty much identical to mine just works.

I think I actually see where the problem is that you are running into. In step 4 of the tutorial it shows code for if they are registered or not and then starts the session:
if (isset($_POST['register'])) { // they want to register
    
$username trim(strip_tags(stripslashes($_POST['username'])));
    if (
ini_get('magic_quotes_gpc')) {
        
$username stripslashes($username);
    }
} else { 
//they don't want to register
    
$random rand(1,1000);
    
$username 'Anon'$random;
//end of if/else conditional</strong>
$num 0;

If you notice, there is a $num = 0; just after that section. Check to see if that is in your code. That makes a big difference.
Stupid fat fiungers.
01000101-01101100-00100000-01000011-01100001-01110010-01100100-01101111-

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #26 on: March 17, 2010, 01:31:09 PM »
	

	
	
$_SESSION['user'] = $username;
	
	
$_SESSION['score'] = 0;
	
	
$_SESSION['correct'] = array(); 
	
	
$_SESSION['wrong'] = array();
	
	
$_SESSION['finished'] = 'no';
	
	
if (isset(
$_SESSION['error']))
	
	
unset(
$_SESSION['error']); 
	
	
$num 0;
	
} else {
	
	
$random rand(1,1000);
	
	
$_SESSION['user'] = 'Anon'$random;
	
	
$_SESSION['score'] = 0;
	
	
$_SESSION['correct'] = array(); 
	
	
$_SESSION['wrong'] = array(); 
	
	
$_SESSION['finished'] = 'no';
	
	
$num 0;
	
}


There is my code. I have the num 0 in there and it still doesnt work!

Offline hcdarkmage

  • Enthusiast
  • Posts: 326
  • Gender: Male
  • I.U.I.Y.G., E.Y.C.B.
    • View Profile
Re: Questions Array not shuffling
« Reply #27 on: March 17, 2010, 01:46:08 PM »
First off, according to the tutorial, your $num=0; is in the wrong place. If you look at the code it looks like this:
if (isset($_POST['register'])) {
    
$username trim(strip_tags(stripslashes($_POST['username'])));
} else {
    
$random rand(1,1000);
    
$username 'Anon'$random;
//end of if/else conditional</strong>
$num 0;
$_SESSION['user'] = $username// username
$_SESSION['score'] = 0// score set to 0
$_SESSION['correct'] = array(); // to hold the user's correct answers
$_SESSION['wrong'] = array(); // to hold the user's incorrect answers
$_SESSION['finished'] = 'no'// they haven't finished the quiz yet


Without knowing your full if-else statement, no one can tell what is going on in that code. It could be that it isn't even calling that if-else statement at all. Plus the includes and placement of your code is important. The tutorial uses 3 pages. it is hard to tell from the snippets of code that you provide whether you have them in the right pages to begin with.
Stupid fat fiungers.
01000101-01101100-00100000-01000011-01100001-01110010-01100100-01101111-

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #28 on: March 17, 2010, 02:46:11 PM »
I moved the two $nums = 0 's and it did nothing. Answer one is still the right one with no change. I didnt even have to copy the code. He gives all the source files for download. All I had to do was take them and modify the questions. But it still doesnt work. I have looked through the entire tutorial like twice and went over the code and there is no difference I really have no idea why it isnt working for me.

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #29 on: March 17, 2010, 03:06:08 PM »
There is obviously something wrong in your code. Attach the files you are using and we can take a look at the full code.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #30 on: March 17, 2010, 03:18:09 PM »
Ok I will put ever single bit of code I am using down. I really appreciate the help guys.

Index.php
<?php //index.php
session_name("Acronym_Test");
session_start();
$_SESSION['score'] = 0;
$_SESSION['correct'] = array(); 
$_SESSION['wrong'] = array();
$_SESSION['finished'] = 'no'
$_SESSION['num'] = 0;
require_once (
'functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test</title>
<script type="text/javascript" src="start.js"></script>
</head>
<body id="splash">
<div id="wrapper">
<div id="intro">
<h1>Take the test and see how well you know your web acronyms</h1>
<p>Each acronym has 4 possible answers. Choose the answer you think is correct and click <strong>'Submit Answer'</strong>. You'll then be given the next acronym.</p>
<p>There are 20 acronyms, so let's get cracking! You'll get your score at the end of the test. It's just like facebook (honest!).</p>
<div id="leaderboard">
<h2>Top 10 Scorers</h2>
<?php 
 showLeaders
('leaders.xml',10,5);
 
?>
</div><!-- leaderboard-->
</div><!--intro-->
<div id="quiz">
<h2>Start The Test</h2>
<p>If featuring on the Score Board is of absolutely no interest to you,</p>
<form id="jttt" method="post" action="test.php">
<p><input type="submit" value="Just Take The Test" /></p>
</form>
<form id="questionBox" method="post" action="test.php">
<p>If you want to be placed on the 'Top Scorers' list, please enter a username below.</p> 
<ul>
<li><label for="username">Create A Username:</label><br />
<input type="text" id="username" name="username" value="Username" />
<p id="exp">Username must be between 3 and 10 characters in length</p></li>
</ul>
<p><input type="hidden" name="register" value="TRUE" />
<input type="submit" id="submit" value="Register And Take The Test" /></p>
</form> 
<p id="helper"><?php if(isset($_SESSION['error'])) echo $_SESSION['error']; ?></p>
</div><!--quiz-->
</div><!--wrapper-->
</body>
</html>


test.php
<?php //test.php

session_name("Acronym_Test");
session_start();
require_once(
'questionsandanswers.php');
require_once(
'functions.php');
if (!isset(
$_POST['submitter'])) {

    if(isset(
$_POST['register'])) {
	
	
$username trim(strip_tags(stripslashes($_POST['username'])));
	
	
$file "leaders.xml";
 
	
	
$xml simplexml_load_file($file);
	
	
foreach(
$xml->user as $user) {
	
	
	
if (
$user->name == $username) {
 
	
	
	
$_SESSION['error'] = 'That name is already registered, please choose another.';
 
	
	
	
header('Location: index.php');
 
	
	
	
exit();
 
	
	
	
}
 
	
	
}
	

	
	
$_SESSION['user'] = $username;
	
	
$_SESSION['score'] = 0;
	
	
$_SESSION['correct'] = array(); 
	
	
$_SESSION['wrong'] = array();
	
	
$_SESSION['finished'] = 'no';
	
	
if (isset(
$_SESSION['error']))
	
	
unset(
$_SESSION['error']); 
	
	
$num 0;
	
} else {
	
	
$random rand(1,1000);
	
	
$_SESSION['user'] = 'Anon'$random;
	
	
$_SESSION['score'] = 0;
	
	
$_SESSION['correct'] = array(); 
	
	
$_SESSION['wrong'] = array(); 
	
	
$_SESSION['finished'] = 'no';
	
	
$num 0;
	
}
} else {
	
$num = (int) $_POST['num'];
	
$postedanswers str_replace("_"," ",$_POST['answers']);
	
if (
$postedanswers == $answers[$num]['0']) {
	
	
$_SESSION['score']++;
	
	
$_SESSION['correct'][] = $postedanswers
	
} else {
	
	
$_SESSION['wrong'][] = $postedanswers;
	

	
if (
$num count($questions)-1) {
	
	
$num++;
	
} else {
	
	
$last true;
	
	
$_SESSION['finished'] = 'yes';
	
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test</title>
<?php 
if (!isset($last)) {
	
echo 
"<script type=\"text/javascript\" src=\"form.js\"></script>";
}
?>
</head>
<body>
<div id="wrapper">
<div id="intro">
<h1>Take the test and see how well you know your web acronyms</h1>
<p>Each acronym has 4 possible answers. Choose the answer you think is correct and click <strong>'Submit Answer'</strong>. You'll then be given the next acronym.</p>
<p>There are 20 acronyms, so let's get cracking! You'll get your score at the end of the test. It's just like facebook (honest!).</p>
<?php if(isset($_SESSION['user'])) echo "<h4>Current tester: {$_SESSION['user']}</h4>"?>
</div><!--intro-->
<div id="quiz">
<?php 
if (!isset($last)) {  ?>
<h2>Acronym <?php echo $num+1?>:</h2>
<p>What does <strong><?php echo $questions[$num]; ?></strong> stand for?</p>
<form id="questionBox" method="post" action="test.php">
<ul>
<?php 
$pattern 
' ';
$replace '_';
shuffle_assoc($answers[$num]);
foreach (
$answers[$num] as $answer) {
	
$answer2 str_replace($pattern,$replace,$answer);
	
echo 
"<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n";
	
echo 
"<label for=\"$answer2\">$answer</label></li>\n";
}
?>
</ul>
<p><input type="hidden" name="num" value="<?php echo $num?>" />
<input type="hidden" name="submitter" value="TRUE" />
<input type="submit" id="submit" name="submit" value="Submit Answer" /></p>
</form>
<?php } else { 
$file "leaders.xml";
 
$xml simplexml_load_file($file);
 
$user $xml->addChild('user');
 
$uname $user->addChild('name',$_SESSION['user']);
 
$uscore $user->addChild('score',$_SESSION['score']);
 
$xml->asXML("leaders.xml");
 
echo 
"<h2 id=\"score\">{$_SESSION['user']}, your final score is:</h2>\n
 <h3>
{$_SESSION['score']}/20</h3><h4>Verdict:</h4>";
 if(
$_SESSION['score'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n";
 if((
$_SESSION['score'] > 5) && ($_SESSION['score'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n";
 if((
$_SESSION['score'] > 10) && ($_SESSION['score'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n";
 if(
$_SESSION['score'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>";
 echo 
"<p id=\"compare\"><a href=\"results.php\">See how you compare! <img src=\"images/arrow.png\" /></a></p>";
}
?>
</div><!--quiz-->
</div><!--wrapper-->
</body>
</html>


functions.php
<?php //functions.php

function shuffle_assoc(&$array) {
	
$keys array_rand($arraycount($array));
	
foreach(
$keys as $key)
    
	
$new[$key] = $array[$key];
	
    
$array $new;
        return 
true;
	
}
  
function 
showLeaders($file,$limit,$group null) { 
	
$leaders = array();
	

	
// Load the xml file and place all users and associated 
 
	
// scores into the 'leaders' array.
 
	
$xml simplexml_load_file($file);
 
	
foreach(
$xml->user as $user) {
 
	
	
$name = (string)$user->name;
 
	
	
$score = (string)$user->score;
 
	
	
$leaders[$name] = $score;
 
	
}
 
	
	

 
	
// Sort the leaders array numerically, highest scorers first.
	

 
	
arsort($leaders,SORT_NUMERIC);
 
	

 
	
// Initialise our $counter variable to '1'.
 
	
$counter 1;
 
	

 
	
// Start a html ordered list to hold the leaders.
 
	
$output "<ul class=\"leaders\">\n";
 
	

 
	
// Loop through the 'leaders' array and wrap each username and score
 
	
// in <li> tags. If the user is the current $_SESSION['user'], wrap
 
	
// the name/score in <strong> tags too.
 
	
foreach (
$leaders as $key => $value) {
 
	
	
// Check that $counter is less than $limit.
 
	
	
if (
$counter <= $limit) {
 
	
	
	
if (
$key == $_SESSION['user']) {
 
	
	
	
	
$output .= "<li><strong>$key:</strong> $value/20</li>\n";
 
	
	
	
} else {
 
	
	
	
	
$output .= "<li>$key$value/20</li>\n";
 
	
	
	
}
 
	
	
	
// Check to see if $group parameter has been passed.
 
	
	
	
// If it has, create separate lists according to the $group variable.
 
	
	
	
if (
$group) {
 
	
	
	
	
// Use the modulus operator(%) to create new sub-list.
 
	
	
	
	
if(
$counter $group == 0) {
 
	
	
	
	
	
$output .= "</ul>\n<ul class=\"leaders\">\n";
 
	
	
	
	
}
 
	
	
	
}
 
	
	
}
 
	
// Increment the $counter.
	

 
	
$counter++;
 
	
}
 
	
// End the ordered list.
 
	
$output .= "</ul>\n";
 
	

 
	
// Print out the ordered list.
	
echo 
$output;
 }
 
function 
showAnswers($answers,$questions) { 
	
for(
$x 0$xcount($answers); $x++) {
	
	
if (
$x == 0) { 
	
	
 
	
$output "<div class=\"qanda clear\">\n";
	
	
} else { 
	
	
	
$output "<div class=\"qanda\">";
  
	
	
}
 
	
$output .= '<h4>Anacronym' . ($x+1) . ': ' $questions[$x] . '</h4>'
	
$output .= "<ol>\n";
 
	
for (
$y 0;$ycount($answers[$x]); $y++) {
 
	
	
if ((
$answers[$x][$y] === $answers[$x][0]) && (in_array($answers[$x][$y],$_SESSION['correct']))) {
 
	
	
	
$output .= "<li class=\"correctuser\">{$answers[$x][$y]} (Correct!)</li>\n";
 
	
	
} else if (
$answers[$x][$y] === $answers[$x][0]) {
 
	
	
	
$output .= "<li class=\"correct\">{$answers[$x][$y]}</li>\n";
 
	
	
} else if (
in_array($answers[$x][$y],$_SESSION['wrong'])) {
 
	
	
	
$output .= "<li class=\"wrong\">{$answers[$x][$y]} (Woops!)</li>\n";
 
	
	
} else { 
 
	
	
	
$output .= "<li>{$answers[$x][$y]}</li>\n";
	
	
}
	
}
	
$output .= "</ol></div>\n";
	
echo 
$output;
	
}
}
?>
	



questionsandanswers.php
<?php
$questions 
= array('FTP','AJAX','RSS','XSS','PHP','W3C','XML','YUI','HTML','CGI','SSL','SQL','HTTP','CSS','SOAP','WAI','SSI','JSON','XSLT','WCAG');
$answers = array(
array(
=>'File Transfer Protocol','Force Through Privately','File Through Protocol','File Test Protocol'),
array(
=> 'Asynchronous JavaScript and XML','All JavaScript and XML','Alternative Java and XML','Actual JavaScript and XML'),
array(
=> 'Really Simple Syndication','Really Simple Scripting','Ready-Styled Scripting','Really Stupid Syndication'),
array(
=> 'Cross-site Scripting','Cross-site Security','Cleverly Structured Scripting','eXtremely Safe and Secure'),
array(
=> 'PHP: Hypertext Preprocessor','Post Hypertext Processor','Practical HTML Processing','Process HTML Prettily'),
array(
=> 'World Wide Web Consortium','World Wide Web Committee','World Wide Web Creatives','Wakefield Willy Wavers Club'),
array(
=> 'eXtensible Markup Language','eXtendable Markup Language','Crossover Markup Language','eXtreme Markup Language'),
array(
=> 'Yahoo User Interface','Yahoo\'s Useful Idea','Yahoo Utility Interface','Yahoo User Interaction'),
array(
=> 'Hypertext Markup Language','Human Markup Language','Helpful Markup Language','Hypertext Memory Language'),
array(
=> 'Common Gateway Interface','Common or Garden Interaction','Computer\'s Graphical Intelligence','Common Graphical Interface'),
array(
=> 'Secure Sockets Layer','Server Security Layer','Server Security Level','Secret Socket Layer'),
array(
=> 'Structured Query Language','Stupid Query Language','Secure Query Language','Strict Query Language'),
array(
=> 'Hypertext Transfer Protocol','Hypertext Traffic Protocol','HTML Traffic Transfer Protocol','HTML Through Traffic Protocol'),
array(
=> 'Cascading Style Sheets','Custom Style Sheets','Clientside Style Sheets','Calculated Style Sheets'),
array(
=> 'Simple Object Access Protocol','Structured Object Access Protocol','Simple, Objective And Private','Simply Obvious Access Principle'),
array(
=> 'Web Accessibility Initiative','World Wide Accessibility Intiative','World Wide Accessibility Incorporation','Web Accessibility and Inclusion'),
array(
=> 'Server-Side Include','Server-Side Intelligence','Scripted Server Include','Secure Server Include'),
array(
=> 'JavaScript Object Notation','JQuery-Scripting Object Notation','Just Simple Object Notation','JavaScript Over the Net'),
array(
=> 'eXtensible Stylesheet Language Transformation','eXpandable Stylesheet Language Transfer','eXtensible Stylesheet Language Transfer','eXtendable Stylesheet Language Transformation'),
array(
=> 'Web Content Accessibility Guidelines','Wakefield Community Action Group','Web Criteria And Guidelines','World-wide Common Access Group')
); 
?>


results.php
<?php //results.php
session_name("Acronym_Test");
session_start();
if(
$_SESSION['finished'] != 'yes') {
header('Location: index.php');
}
include_once(
'questionsandanswers.php');
include_once(
'functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test Results</title>
</head>
<body id="resultpage">
<div id="wrapresult">
<h1>The Results Page For <span><?php echo $_SESSION['user']; ?></span></h1>
<div id="intro">
<h2>Top 20 Scorers</h2>
<?php showLeaders('leaders.xml',20); ?>
</div><!--intro-->
<div id="quiz">
<?php showAnswers($answers,$questions); ?>
	

</div><!--quiz-->
<ul id="footer" class="clear">
<li><a href="index.php" title="Start The Quiz Again">Start Again</a></li>
<li><a href="http://www.elanman.co.uk/2009/03/make-your-own-php-quiz-part-1/" title="Return To ElanMan's Drawers">Return To The Blog</a></li>
</ul>
</div><!--wrapper-->
</body>
</html>


leaders.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user>
  
	
<name>Bobby</name>
    <score>10</score>
  </user>
  <user>
  
	
<name>Billy</name>
    <score>1</score>
  </user>
</users>


start.js
window.onload = function () {
	
document.getElementById('username').onfocus = function(evt) {
	
	
if(
this.value == 'Username'this.value '';
	
	
document.getElementById('helper').innerHTML '';
	
	
}
	
document.getElementById('username').onblur = function(evt) {
	
	
if(
this.value == ''this.value 'Username';
	
	
}
	
document.getElementById('questionBox').onsubmit = function() {return checkForm();};
}

function 
checkForm() {
	
if ((
document.getElementById('username').value == '') || (document.getElementById('username').value == 'Username') || (document.getElementById('username').value.length 3) || (document.getElementById('username').value.length 10)) {
	
document.getElementById('helper').innerHTML 'To register, please enter your own username between 3 and 10 characters in length';
	
	
return 
false;
	
}
}


form.js
window.onload = function () {
	
document.getElementById('submit').disabled true;
	
var 
qform document.getElementById('questionBox');
	
var 
inputs qform.getElementsByTagName('input');
	
for(var 
0inputs.length;i++) {
	
	
inputs[i].onclick = function(evt) { checkForm();};
	
}
}

function 
checkForm() {
	
document.getElementById('submit').disabled false;
}


Thats EVERYTHING every single bit of code involved in this. Thanks for the help. Any help you can give would be amazing!

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #31 on: March 17, 2010, 05:25:03 PM »
There was a CSS file as well but that shouldn't matter right?

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #32 on: March 18, 2010, 08:26:52 AM »
Was any of this helpful? Any idea from my mass of code what is causing the problem?

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #33 on: March 18, 2010, 10:30:10 AM »
I just noticed you can attach files. Here is all the source files downloaded all ready to go. I havn't touched them at all. They just dont shuffle for me.
Sorry I didn't post this before. I just noticed now that you can include files.

[attachment deleted by admin]

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #34 on: March 18, 2010, 11:24:35 AM »
There is obviously something wrong in your code. Attach the files you are using and we can take a look at the full code.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #35 on: March 18, 2010, 11:25:58 AM »
I did attach it. Look at the post directly above that one you posted. There is a zip file that contains everything.

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #36 on: March 18, 2010, 11:40:09 AM »
Yes, I DID see that. I was responding to your statements "I just noticed you can attach files ... I just noticed now that you can include files." Funny how you just noticed that today when I mentioned it yesterday.

I already copied the code from your post yesterday. I just haven't had the time to sift through it.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #37 on: March 18, 2010, 11:44:20 AM »
I know I am a dofus. I thought by attach you meant just put it down. I dont know why. My head is away these past couple of days. I was posting earlier and noticed the attach thing. Sorry. But I really appreciate the help thanks.

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #38 on: March 22, 2010, 09:42:00 AM »
Have you had any luck mjdamato? or had a chance to look over the code at all yet?

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #39 on: March 22, 2010, 11:41:43 AM »
Have you had any luck mjdamato? or had a chance to look over the code at all yet?

Upon initial inspection it did seem to present the same problem, but then after playing around with it for a while it seemed to work correctly. I have to assume that it has something to do with the SESSION variables. I haven't had time to dive into it more. Personally, it wouldn't be worth my time. I could probably rewrite a better solution in less time than it would take to fix that code. But, I just don't have the time right now.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #40 on: March 22, 2010, 11:45:15 AM »
You cant post the code you messed about with to get it working or anything? or what you changed to get it working correctly?
?

Offline Psycho

  • Guru
  • Freak!
  • *
  • Posts: 7,753
    • View Profile
Re: Questions Array not shuffling
« Reply #41 on: March 22, 2010, 12:27:54 PM »
You cant post the code you messed about with to get it working or anything? or what you changed to get it working correctly?
?

Well, I was only modifying the code to output data to the screen so I could see some of the internal variables to see what was going on. When it started to work I undid my changes, and it continued to work. So, the problem was not "fixed" by anything I did. That is why I assume it has something to do with the session variables.
The quality of the responses received is directly proportional to the quality of the question asked.

I do not always test the code I provide, so there may be some syntax errors. In 99% of all cases I found the solution to your problem here: http://www.php.net

Offline doctor-EggmanTopic starter

  • Irregular
  • Posts: 43
    • View Profile
Re: Questions Array not shuffling
« Reply #42 on: March 22, 2010, 12:33:32 PM »
Alrighty. Well thanks for all the help much appreciated.

Offline lynxjava

  • Irregular
  • Posts: 1
    • View Profile
Re: Questions Array not shuffling
« Reply #43 on: April 27, 2010, 05:18:32 PM »
Hey guys,

I dont know what the big deal is.
The answer is really simple and you guys just missed out a line.
Just copy and paste this code and it would work fine.

I have highlighted in bold the missing line which should of been included.

function shuffle_assoc(&$array) {
   $keys = array_rand($array, count($array));
   shuffle($keys);
   foreach($keys as $key)
       $new[$key] = $array[$key];
       $array = $new;
        return true;
   }


I found the answer by looking up some coding on the php.net

Hope this solved your problems :)