2

I am trying to generate variable name dynamically in php for loop. I want call a function within for loop and want to pass iterated values. What I tried is:

for ($i=1, $j=1; $i<=16 ; $i++, $j++) {
    $a='arrtreelevel_1';
    $b='0';
    $newname = $a.$j.$b;
    echo $newname,"<br>";
    echo $arrtreelevel_1[0];
    $arrtreelevel_2.$i = profiledetails($newname);
}

My problem is '$newname' variable printing $arrtreelevel_1[0] as a text not taking the value, and $arrtreelevel_11[0] returns the actual value. I tried with echo ${'arrtreelevel_1$i'} also which printing nothing. Assist me with any solution please.

Thanks in advance.

1
  • you need to use double quotes instead of single quotes ${"arrtreelevel_2$i"} Commented Jul 7, 2017 at 11:10

2 Answers 2

6

you need to use double quotes instead of single quotes

${"arrtreelevel_2$i"}=profiledetails($newname);
Sign up to request clarification or add additional context in comments.

Comments

1

Use $$ to make runtime php variable. Replace this line

$arrtreelevel_2.$i = profiledetails($newname);

To

$tempvar = $arrtreelevel_2.$i;
$$tempvar = profiledetails($newname);

2 Comments

I am getting values for $arrtreelevel_2.$i properly as arrtreelevel_21,arrtreelevel_22 and son on.But $newname is printing $arrtreelevel_21 but actual $arrtreelevel_21value is 61 which i wanted.not the name of concatinated variable but the value of it
@Webbie : $tempvar will give you name $arrtreelevel_21 and $$arrtreelevel_21 using $$ will give you value of $arrtreelevel_21

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.