Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate PHP variable name?

Tags:

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?

like image 354
Smudger Avatar asked Jul 31 '12 12:07

Smudger


People also ask

How do I concatenate a PHP variable in HTML?

The first is the concatenation operator ('. '), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator (' . = '), which appends the argument on the right side to the argument on the left side.

Can you concatenate strings in PHP?

Prepend and Append Strings in PHPYou can use the concatenation operator . if you want to join strings and assign the result to a third variable or output it. This is useful for both appending and prepending strings depending on their position. You can use the concatenating assignment operator .

Which below operator is used for concatenation in PHP?

1. Concatenation Operator ("."): In PHP, this operator is used to combine the two string values and returns it as a new string.


2 Answers

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; } 
like image 170
Tim Cooper Avatar answered Oct 26 '22 22:10

Tim Cooper


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"; 
like image 31
Adunahay Avatar answered Oct 26 '22 21:10

Adunahay