40

I have a file named questions.php with an array as follows :

$question12 = array("Which is the tallest mountain","Mt Everest");

I am including this file in another file as follows :

require_once('questions.php');
$var = 12;
$question = '$question'.$var.'[0]';
echo $question;

The above code just outputs the following string (not the contents of the variable):

$question12[0]

But I want the variable $question to contain the string present in $question12[0].

How do I accomplish this?

3
  • Just use $question12[0] Commented Jun 6, 2013 at 6:38
  • why not just use $question12[0] Commented Jun 6, 2013 at 6:38
  • of course ...directly using $question12[0] works..but that's not that point.. i want to generate a php variable .. and i am stuck.. Commented Jun 6, 2013 at 6:39

4 Answers 4

88

Variable variable is not recommended, but the answer is below:

$question = ${'question'.$var}[0];
Sign up to request clarification or add additional context in comments.

4 Comments

Why is variable variable not reccommended?
@Piersv maybe because dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7, and the fact that this can always be circumvented by using an array. I do not see other downsides.
Variable Variables work fine in PHP 5.6 and @jordan-doyle gave the best answer below.
@Chiwda Is this equally good for PHP 8?
6

You're looking for variable variables.

$id = 12;
$q = "question{$id}";
$q = $$q[0];

You should seriously consider looking into multidimensional arrays to stop having multiple arrays.

Comments

4

Just use $question12[0]. It will give you the desired output.

Using the $var you can do it like this:-

$question = ${'question'. $var}[index];

Comments

4

Sorry, im going to get some hate for mentioning something evil but still it is one of the options

<?php
$question12 = array("Which is the tallest mountain","Mt Everest");
$var = 12;
$question = '$question'.$var.'[0]';
eval("echo $question;");
?>

P.S: eval() is that evil

1 Comment

rename_function('eval', 'evil'); now ypu can use the function evil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.