How to concatenate PHP variable name?
Solution 1
The proper syntax for variable variables is:
${"check" . $counter} = "some value";
However, I highly discourage this. What you're trying to accomplish can most likely be solved more elegantly by using arrays. Example usage:
// Setting values
$check = array();
for ($counter = 0; $counter <= 67; $counter++){
echo $counter;
$check[] = "some value";
}
// Iterating through the values
foreach($check as $value) {
echo $value;
}
Solution 2
This is usable in some cases. For example if your app has something like 2 language entries in DB.
echo $this->{'article_title_'.$language};
That's much more usable than for example this;
if($language == 'mylanguage1')
echo $this->article_title_mylanguage1;
else
echo $this->article_title_mylanguage2;
Obviously this is what you should not have to do in your multilingual app, but i have seen cases like this.
Solution 3
You should use ${'varname'} syntax:
for ($counter=0,$counter<=67,$counter++){
echo $counter;
${'check' . $counter} ="some value";
}
this will work, but why not just use an array?
$check[$counter] = "some value";
Related videos on Youtube
Smudger
Updated on August 22, 2022Comments
-
Smudger over 1 year
I have a PHP for loop:
for ($counter=0,$counter<=67,$counter++){ echo $counter; $check="some value"; }
What I am trying to achieve is use the for loop variable and append it to the name of another variable.
Bascially, I want the PHP output to be as follows for each row
1 $check1="some value" 2 $check2="some value" 3 $check3="some value" 4 $check4="some value" etc etc
I have tried
$check.$counter="some value"
but this fails.How can I achieve this? Am I missing something obvious?
-
Matt over 11 yearsWould the use of an
array
be preferable to this method?$myVar = array(); for($i = 0; $i <= 67; $i++) { $myVar[] = "Some Value"; }
-
-
Smudger over 11 yearsThanks Tim, is there a situaton when this is acceptable or is it functionality no longer used?
-
Tim Cooper over 11 years@Smudger: Off the top of my head, I can't think of a solid case where one would use variable variables. Looking at the comments on the documentation page might give you some ideas on where they could be useful. Just keep in mind that what you read there may not be considered best practice.
-
Nosajimiki almost 7 yearsConcatenation is never the "cleaner" solution, but there may be cases where you have old, highly developed code that was never intended to correlate A+B where it is simply much easier to do this than rewriting hundreds of lines of code just to replace old variable types with arrays
-
Nosajimiki almost 7 yearsThe one case I can think of where I use them is with HTML forms where I have recursively built inputs. When you Post it, it will post as a bunch of variables and not as an array; so, recursively calling them may be easier with $_POST[${"myInputName".$i}]
-
Pathros over 5 yearsYeah, it is my case: I got 3 columns entries in DB. So i need to loop like that from a checkboxes group