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?
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.
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 .
1. Concatenation Operator ("."): In PHP, this operator is used to combine the two string values and returns it as a new string.
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; }
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With