Reputation: 3323
I have the following code:
echo"<input name=\"q". $i. "\" value=\"4\" id=\"q1a1\" type=\"radio\" ";
if ($results['q1']==4) echo "checked"
echo";
/>";
Edit: Added the echo statement, which is why the \
are in situ.
The part $results['q1']
I'd like the 1
of the 'q1'
to be a variable - this doesn't seem to have the desired effect:
if ($results['q".$i."']==4) echo "checked"
Upvotes: 0
Views: 56
Reputation: 5239
ou can either do
if ( $results["q".$i] == 4 ) echo "checked"; // .(dot) operator concatenates strings/variables.
or
if ( $results["q$i"] == 4 ) echo "checked"; // double-quotes evaluates variables inside them.
Upvotes: 0
Reputation: 956
you want to write:
if ($results["q".$i]==4) echo "checked"
the "." operator will concatenate 2 strings to make a string and an associative array takes a string. Moreover variable inside ' (quote) operators won't be parsed (that's the difference between " and ') so '$i' will just give a string $i.
Upvotes: 0
Reputation: 956
if ($results['q'.$i]==4) echo "checked"
this prevents issues with string interpolation. Wouldn't really be an issue in this case, but I feel better staying away from it, as it makes code look dirtier to me.
Upvotes: 0
Reputation: 21856
if you put the string and variable in double quotes, the whole thing is evaluated to 1 variable:
if ( $results["q$i"] == 4 ) echo "checked"
Upvotes: 4