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:

$a=1;
echo "$a";

The array member can also be embedded in a string:

$a=array(1,2,3);
echo "$a[0]$a[1]$a[2]";//123

What if the key of the array is string?

$a=array("a"=>1,"b"=>2,"c"=>3);
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:

$a=array("a"=>1,"b"=>2,"c"=>3);
echo "$a[a]$a[b]$a[c]";//123

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

$a=array("a"=>1,"b"=>2,"c"=>3);
echo "{$a['a']}{$a['b']}{$a['c']}";

or this:

$a=array("a"=>1,"b"=>2,"c"=>3);
echo "{$a["a"]}{$a["b"]}{$a["c"]}";

 

But you cannot use this:

$a=array("a"=>1,"b"=>2,"c"=>3);
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();
$a->a=1;
$a->b=2;
echo "{$a->a}{$a->b}";//12
echo "$a->a$a->b";//12

 

Posted in

Comments are closed, but trackbacks and pingbacks are open.