Reputation: 145
I Have the php code :
$rand = rand(1,5);
and I want to define var that has the name of the rand function like :
$$rand // if $rand= 1 then the var will be $1
and then do
switch($rand){
case(1):
$$rand = 'How many legs dog has ?';
$ans= '4'; }
The code is for defining security questions. Hope someone got my idea. How can I do it ?
Upvotes: 1
Views: 2817
Reputation: 9302
// Sanitize the arrays
$questions = array();
$answers = array();
// Build some questions and assign to the questions array
$questions[0] = 'How many legs does a dog have?';
$questions[1] = 'How many eyes does a human have?';
$questions[2] = 'How many legs does a spider have?';
// Add the answers, making sure the array index is the same as the questions array
$answers[0] = 4;
$answers[1] = 2;
$answers[2] = 8;
// Select a question to use
$questionId = rand(0, count($questions));
// Output the question and answer
echo 'questions: ' . $questions[$questionId];
echo 'answer: ' . $answers[$questionId];
Variables in PHP cannot start with a number.
Upvotes: 1
Reputation: 3675
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
<?php
$a = 'hello';
?>
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
<?php
$$a = 'world';
?>
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:
<?php
echo "$a ${$a}";
?>
produces the exact same output as:
<?php
echo "$a $hello";
?>
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.
Upvotes: 3
Reputation: 2635
${$rand} is the right way. Do note, however, that your variable name cannot start with a number.
Quoting the php manual:
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Upvotes: 0