This has a lot of answers on other pages of stackoverflow, like this question however none of them seem to work for me.
I've this small piece of code as:
echo $optionss='$'."q_option".$de;
In above code, i have a few variables by the name of "q_option0"
, "q_option1"
, "q_option2"
... up to "q_option4"
. $de
is a variable that holds count from 0-4.
Now i want to print $optionss= $q_option0
(this is in a for loop to get the increment of last number upto 4), but i'm unable to do so!
Please suggest me what i'm doing wrong!!
I Think you dint process the array $de. you can use foreach or for loop .Try this .
<?php
$de=array(1,2,3,4);
foreach($de as $val){
echo $optionss='$'."q_option".$val."<br>";
}
?>
or use single quotes as given
<?php
$de=array(1,2,3,4);
foreach($de as $val){
echo $optionss='$q_option'.$val."<br>";
}
?>
or try this
<?php
$dollar="$";
$de=array(1,2,3,4);
foreach($de as $val){
echo $optionss=$dollar.'q_option'.$val."<br>";
}
?>
output
$q_option1
$q_option2
$q_option3
$q_option4
Use single quote to print special characters
'$q_option'.$de;
Also you have forgotten to place $optionss within single quotes if you do not want its value printed out.
echo '$optionss= $q_option'.$de; // print the whole expression
But if you do this..
echo $optionss='$'."q_option".$val."<br>"; // assign right hand side of the expression to the variable '$optionss' and print that out
// so you will only get output $q_option0, $q_option1... instead of $optionss=$q_option0, $optionss=$q_option1....
Below is solution to a different problem as I misunderstood it:
I assume its to dynamically create variable names and read their values
you can either create a temporary variable with the value as the name of the variable you want to access and then use double $$ to access the value of the variable inside the variable. Make sense?
$tmp = "q_option".$de;
echo $optionss=$$tmp;
If "q_option0", "q_option1", "q_option2" etc are variables, then you reference the value of these varaibles with $$
. This will output "abc". Note that the variable $optionss
is being assigned the value of the variable $q_option0
in this code at the same time as its value is being echoed.
$de = 0;
$q_option0 = "abc";
$var = "q_option".$de;
echo $optionss = $$var;
Remove the doller symbol '$'and use double $$ to access the value of the variable.
Assume $q_option0 = "400";
Try This :
<?php
$q_option0 = "400";
$de = 0;
$optionss="q_option".$de;
echo "Your Output: " . $$optionss;
Output :
Your Output: 400