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
https://forums.phpfreaks.com/topic/77691-array-questionanswer/
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
https://forums.phpfreaks.com/topic/77691-array-questionanswer/#findComment-393281
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
https://forums.phpfreaks.com/topic/77691-array-questionanswer/#findComment-393282
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
https://forums.phpfreaks.com/topic/77691-array-questionanswer/#findComment-393285
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
https://forums.phpfreaks.com/topic/77691-array-questionanswer/#findComment-393361
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.