how to refer to array member in string?

We know that we can refer to a variable in a string; the variable will be expanded to its value:

echo "$a";

The array member can also be embedded in a string:

echo "$a[0]$a[1]$a[2]";//123

What if the key of the array is string?

echo "$a['a']$a['b']$a['c']";//error
echo "$a["a"]$a["b"]$a["c"]";//error

The above example will cause syntax error. In fact you should use this:

echo "$a[a]$a[b]$a[c]";//123

,i.e.,don’t quote the key. You can also use this:

echo "{$a['a']}{$a['b']}{$a['c']}";

or this:

echo "{$a["a"]}{$a["b"]}{$a["c"]}";


But you cannot use this:

echo "{$a[a]}{$a[b]}{$a[c]}";

which gets warnings “Use of undefined constant a,b,c”.

To embed object properties in string is also allowed:

class A
  var $a;
  var $b;
$a=new A();
echo "{$a->a}{$a->b}";//12
echo "$a->a$a->b";//12


Posted in

Comments are closed, but trackbacks and pingbacks are open.