php make a variable with a variable
I’m not sure if this is possible, but I have a counter variable which increases by one every time. Now I have a couple of variables above the counter which have a number after them e.g.
now inside the counter I would like the number after the variable to increase with the counter variable. so like
What I don’t want is a string, I just want a number after a variable to change everytime the counter variable goes up by one.
5 Answers 5
This is called a variable variable. Any time you think about using one, realise that you should use an array instead.
Thank you but i can’t use an array right now, if I changed some of the previous code which I got of a website, and I just want to test something out before I change it 🙂
@mario — it is also an answer since it links to the documentation which explains how to do what was asked.
Not sure what you mean by no string, but this should do it.
But I agree that a different method (array) should be used instead.
What are you trying to do with this?
I ask because it looks like you’d be better off using an array to achieve what you want. Then you could do something like:
You’ll want to change that code to this:
for ( $counter = 1; $counter = $var; >
Wrapping the string in braces allows you to use it to dynamically create a variable name, so we simply concatenate «var» with the counter value, and then use it as the new variable name.
However, note that doing this will create and initialize all of the variables along the way. So in this example, you’ll end up with $var, $var1, and $var2 all equal to the same value. If this is not what you want, you will have to unset() all of the variables you don’t want.
Also note, however, that this is not a «best practice» in most cases. May I ask why you need to do this? Perhaps an array would be more suitable..
how to add a variable in another variable?
this must be simple for most, how to add a variable in another variable? this variable $objResult[«price»] has a value of 5 :
echo $objResult["price"]; //it shows `5`
$newVariable = $objResult["price"]; echo $newVariable; //nothing happens
This is not working for me. echo $newVariable; it’s not showing anything. but this way it does not work. I tried:
$newVariable = echo $objResult["price"]; $newVariable = print $objResult["price"]; $newVariable = echo $;
$newVariable = $objResult["price"]; echo $newVariable;
This is a terrible question. First of all, you say $newVariable = $objResult[«price»]; doesn’t work, but you’re wrong. If you mean you want to get a variable named $5 out of this. you want variable variables and you should use $ = ‘your value’ like in your last example, but without the echo and the other way around.$objResult['price']>
$objResult[«price»]; is from DataBase. i need to make some math with those data, that comes from DB, and i decided to make simple VARIABLE from them, but it looks it doesn’t work!
3 Answers 3
$newVariable = $objResult["price"]; echo $newVariable;
this is not working for me: if i make echo $objResult[«price»]; it shows 5, but if i make in the way you submited, its not showing anything
I know it looks strange, but it is really a stupid problem. I tried same think about 20 times, and it doesnt work. I knwo this way should work, i tried it first time, but its not working.
Your first attempt (given below) is correct for assigning the value to another variable.
$newVariable = $objResult["price"];
Now, if you want to print this value, you can do:
Otherwise, if you are experiencing some other issue, please update your question 🙂
You said that this didn’t work:
$newVariable = $objResult["price"]; echo $newVariable;
Yet that’s you accepted answer. If somebody else comes here with a similar problem I’ll show how the above may not work. I’m not saying this is the case of the OP, I don’t freaking know what is the case of the OP.
If the value of $objResult[«price»] is is not an string then when you call echo on it it may be calling __toString() on it. This is documented beviour described at Magic Methods at php.net.
So, when you call echo on an object it will convert it to string automatically.
echo $objResult["price"].__toString();
On the other hand when you have the code:
$newVariable = $objResult["price"]; echo $newVariable;
It will be equivalent to this:
$newVariable = $objResult["price"]; echo $newVariable.__toString();
If the first works and the second don’t, then it means that you have an odd implementation of __toString() . You could mitigate the problem by doing the following:
$newVariable = $objResult["price"].__toString(); echo $newVariable;
Variable within variable possible?
I am trying to create a loop statement for some of my code and am wondering how I can put a variable within another variable.
For example:
EDIT
Yes I am aware that my INITIAL form was flawed in the way I captured information (as individual variables as opposed to arrays) so any answer telling me that SESSION is an array and so on is irrelevant because I cannot call any variables implicitly from the SESSION variables I created (without a line by line reference) All variable stored in SESSION are completely unique and independent of each other.
Ack. Your variable naming confuses me greatly. I’m not quite sure what you’re going for. can we try a more concise code sample that, rather than being your application code, contains just the principle you’re going for?
not sure why the question was confusing or why it deserved a -1? I think there are a alot of people who previously did not understand arrays would benefit
@JM4: You already have the solution to your problem in the code. After all $_SESSION is just that: a variable that includes other variables.
@Konrad Rudolph — it does not for the following reason: I store everything in SESSION without any variable names so in order to call the 16th person’s city, I would have to write $_SESSION[‘F16City’] and write out tons of code which is exactly what I was trying to avoid.
@JM4: That’s not what I mean. You don’t need to use $_SESSION (in fact you should not) but $_SESSION is essentially the same as your solution (i.e. an associative array). The same, in fact, as $names in the solution that you accepted below.
6 Answers 6
what about arrays? more: arrays of objects?
+1: Arrays are the correct way to solve this problem. More specifically, $_SESSION can store arrays just as easily as single values, so why not just set/retrieve an array from it instead?
Didn’t test the code myself but perhaps something like:
FirstName"]; $names[$j]['mi'] = $_SESSION["FMI"]; $names[$j]['lname'] = $_SESSION["FLastName"]; > ?>
Then you have an array with arrays of the userinfo
I think this would work well but I am just so unfamiliar with how to then call on each individual variable (I am currently printing $f1fname on a PDF file by specific location and so on with over 300 variables. Not quite sure how to do this using arrays.
I think this would normally work but want to run by how I’m using this. I place each variable (1st person first name) at X and Y coordinates on the page. I am unable to ‘loop’ the write statements because they X and Y coordinates different for every single variable so while I can change the name of the variable being input to $names[1][‘fname’], I am not sure of the benefit when compared to $f1fname. Thoughts?
php wont parse variables inside single quotes ‘, use double quotes » and try this format.
. this is actually supported? Ew, ew, ew. +1, since it answers the original question well, but please, please, please, no one ever actually do this.
@Matchu — why do you dislike this answer? It actually accomplishes every goal I am trying to go for but am curious why it is bad practice.
Arrays are a standard way of accomplishing what you want, and you see it everywhere in the wild. This format never, ever appears in the wild, and for good reason: this is what arrays are for. As such, arrays come with all the extra goodies like free iteration and array_search and the like. No need to duplicate the functionality of arrays while robbing yourself of extra behavior and confusing any future developer (trust me, I’d be stumped for a good 15 minutes).
Php variable in a variable
funny thing is I tried doing it without the quotes but I was looking at the wrong output the entire time. thanks!
You’d not put any quotes around $field . like this:
Variables are not expanded in single quotes; they are only expanded in double quotes or in the heredoc syntax:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
So either use double quotes or, even better, just omit them:
Single quotes inhibit variable substitution.
The latter is highly recommended as it does not require PHP to parse $row[«$field»] into $row[$field] . Saves you some microtime in each iteration.
@thephpdeveloper: Give me 100 developers who prefer the latter and I’ll give you 100 who prefer the former. That edit was useless as the OP can choose for himself which solution appeals to him and whether or not micro optimization is needed.
$row[«$field»] makes sure your key value is a string. But if you’re using $row[«$field»] , please write is as $row[«»] as a standard. Another example: «My name is and I’m years old.»`$field>
@Fake Code Monkey Rashid, give me 100 developers who prefer $row[«$field»] . I’d seriously doubt you’d find them. This is not really a preference. Without quotes is much better for three reasons: 1. less code to write. 2. less processing 3. less code to understand or possibly misinterpret. Would you ever write $a = «$b»; ? If not, why would you ever write $row[«$field»]; ?
@Amil, if you’re worried about type safety, you should be more explicit before that point anyway. $row[«»] is just completely tortured and over the top.$field>
@Mike Sherov: Did you forget that PHP was like a call to the West. Every end user and his sister packed up a wagon to become a web developer. Given that, do you honestly think I can’t find 100 who prefer the former? As for your 3 points, it is a mistake to think that everyone is like you. For some it is preferable to write MORE core to enhance readability even if they lose microseconds in the process. But understand, I did not state that one version was more correct than the other, I merely stated that the OP can choose for himself.
How to insert variable inside variable
$$rand is valid syntax in PHP; however, $1 is not a legal variable name. Try $rand=»r».rand(1,5);$$rand .
3 Answers 3
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:
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.
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:
produces the exact same output as:
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: $ for the first case and $[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.