Search code examples
phparraysstringdouble-quotessquare-bracket

How to make a string resembling an array name with double quote in php


I want to make a string variable -namely

$myvar

whose value may be something like this:

$myvar='somename[5]';

and I get the "somename" and "5" from separate varibale:

i.e.

$name="somename";
$id=5;

and finally I want to make $myvar with an expression using double quote like this:

$myvar="$name[$id]";

but the result is not what I expect. in fact this expression is read as:

$myvar=somename[5];

that is null. Is there any way to simply get "somename[5]" by using double quote in php?

thank you very much


Solution

  • Try the below:

    $myvar= $name."[".$id."]";
    

    or

    $myvar = "{$name}[$id]";