Jump to content

array question/answer


kellz

Recommended Posts

I was trying to make a script that would display a question and under it would be the answer:

 

<?php
$qa = array(
           "q" => array('sean is', 'kelsey is', 'I love'),
	   "a" => array('kelseys bf', 'seans gf', 'sean')
	   );
	   

$answer=shuffle($qa['q']); 
echo $qa['q'][0]; 
echo $qa['a'][$answer]; 
?>

 

Well $answer was supposed to store the array index it had chosen like 0 would be "sean is" so the answer would be "kelseys bf".. the answer is always under the question. But $answer always returns 1 ::)

Link to comment
Share on other sites

If question is always under the answer, use the same numerical index:

 

<?php
$qa = array(
           "q" => array('sean is', 'kelsey is', 'I love'),
	   "a" => array('kelseys bf', 'seans gf', 'sean')
	   );
$answer=rand( 0, count($qa[q])-1 ); 
echo $qa['q'][$answer] .' '; 
echo $qa['a'][$answer];
?>

 

PhREEEk

Link to comment
Share on other sites

thx, it works.. but why didn't this work..

 

shuffle($qa['q']);
$question = $qa['q'][0];
$answer= array_keys($qa["q"], $question); 
echo $question;
echo $answer;

 

array_keys is supposed to know where where the question is in the array

Link to comment
Share on other sites

You have 2 arrays, $qa['q'] and $qa['a']. You are only shuffling $qa['q'], which re-orders the keys. In that respect, the questions and answers are no longer paired because you re-ordered one of the arrays. In the randomness of things, one of the re-ordering PHP might select would be the original order (a much larger array would reduce this chance).

 

At any rate, you want to pick a random item from the array, not randomize the entire array.

 

PhREEEk

Link to comment
Share on other sites

try

<?php
$qa = array(
           "q" => array('sean is', 'kelsey is', 'I love'),
	   "a" => array('kelseys bf', 'seans gf', 'sean')
	   );
$keys = array_keys($qa['q']);
shuffle($keys);
$question = $qa['q'][$keys[0]];
$answer= $qa['a'][$keys[0]]; 
echo $question;
echo $answer;
?>

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.