1

Is it possible to add or concatenate something into a variable name in a PHP variable? For example:

for($g = 7; $g <= 10; $g++){
    for($i = 0; $i <= 4; $i++){
        $counter = $g - 7;
        if($i != $counter){
            continue;
        } else {
            $grade.[$g] = $grades[$i];
        }
    }
}

I want this to happen:

$grade7 = 0
$grade8 = 1
$grade9 = 2
$grade10 = 3
2
  • For such purposes use arrays Commented Oct 13, 2016 at 8:51
  • $$ is your answer Commented Oct 13, 2016 at 8:53

4 Answers 4

1

Concatenates the $g with grade and make this value a variable by adding a $ sign at the starting line...

The example given below:

for($g = 7; $g <= 10; $g++){
    for($i = 0; $i <= 4; $i++){
        $counter = $g - 7;
        if($i != $counter){
            continue;
        } else {
            ${"grade".$g} = $grades[$i];
        }
    }
}

echo $grade7; // 0
echo $grade8; // 1
echo $grade9; // 2
echo $grade10;// 3
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I have been looking for. Thank you
1

One solution would be to create the variables dynamically:

for ($g = 7; $g <= 10; $g++) {
    for ($i = 0; $i <= 4; $i++) {
        $counter = $g - 7;
        if ($i == $counter) {
            ${'grade' . $g} = $grades[$i];
        }
    }
}

Comments

0

You should use ARRAY instead of your method. :)

Try to look at variable named like "$$".

EDIT: Maybe something like

var $array = array();
for($g=7; $g<=10; $g++)
{
    for($i=0; $i<=4; $i++)
    {
        $counter = $g - 7;
        if($i != $counter) continue;
        else $array[$grade.[$g]] = $grades[$i];
    }
}

Comments

0
 $data = new Array();
 for($g = 7; $g <= 10; $g++){
        for($i = 0; $i <= 4; $i++){
            $counter = $g - 7;
            if($i != $counter){
                continue;
            } else {
                $data[$grade.[$g]] = $grades[$i]);
            }
        }
    }

1 Comment

$data = array(); would also be possible

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.