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

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Comments are closed, but trackbacks and pingbacks are open.