0

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"

4 Answers 4

4

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"
0
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.

0

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.