Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to an array name (php)?

Tags:

php

I have 4 arrays, each with a question and answer. I want to select a random question/answer array. Here is my code:

<?php
$query_1 = array("What is two plus three?", "5");
$query_2 = array("What is four plus two?", "6");
$query_3 = array("What is seven plus one?", "8");
$query_4 = array("What is six plus three?", "9");

$rand_key = rand(1,4);
$current_query = ('$query_'.$rand_key);
$question = $current_query[0];

print $question;
?>

$question simply prints "$" rather than the first element of the array. How do I get $question to print the first element of the array?

-- yes, I'm a php noob.

like image 607
jshock Avatar asked Mar 17 '26 07:03

jshock


1 Answers

This is probably a more straight-forward way of accomplishing your task. Instead of storing each question in its own array and fetching it dynamically (i.e. 'question' . $random_value) store each question and answer in the same array and take advantage of array_rand().

<?php
$questions[] = array("What is two plus three?", "5");
$questions[] = array("What is four plus two?", "6");
$questions[] = array("What is seven plus one?", "8");
$questions[] = array("What is six plus three?", "9");

$randomKey = array_rand($questions); // Returns a random key from $questions
$question = $questions[$randomKey];

print $question[0]; // Question
print $question[1]; // Answer
like image 169
Mike B Avatar answered Mar 18 '26 22:03

Mike B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!