How to echo element of associative array in string

2019-01-20 15:39发布

I know It's a very basic question but I have to ask.

I have an associative array let's say it is:

 $couple = array('husband' => 'Brad', 'wife' => 'Angelina'); 

Now, I want to print husband name in a string. There are so many ways but i want to do this way but it gives html error

$string = "$couple[\'husband\'] : $couple[\'wife\'] is my wife.";

Please correct me if I'm using a wrong syntax for backslash.

8条回答
再贱就再见
2楼-- · 2019-01-20 15:53

Your syntax is correct.

But, still you can prefer single quotes versus double quotes.

Because, double quotes are a bit slower due to variable interpolation.

(variables within double quotes are parsed, not the case for single quotes.)

A more optimized and cleaned version of your code:

$string = $couple['husband'] .' : ' . $couple['wife'] .' is my wife.';
查看更多
你好瞎i
3楼-- · 2019-01-20 15:53

You can simply do:

$string = "{$couple['husband']} : {$couple['wife']} is my wife.";

Or:

$string = $couple['husband'] . " : " . $couple['wife'] . " is my wife.";
查看更多
不美不萌又怎样
4楼-- · 2019-01-20 16:00

try this

 <?php $string = $couple['husband']." : ". $couple['wife']." is my wife."; 
  echo  $string//Brad : Angelina is my wife.
 ?>
查看更多
Summer. ? 凉城
5楼-- · 2019-01-20 16:03

Try like

$string = $couple['husband']." : ".$couple['wife']." is my wife.";
查看更多
孤傲高冷的网名
6楼-- · 2019-01-20 16:03

Checkout the solution -

$string = "$couple[husband] : $couple[wife] is my wife.";

as you can see you have to remove single quotes and backslashes if you are using the entire string inside double qoutes.

A much better approach will be -

$string = $couple[husband].' : '.$couple[wife].' is my wife.';

查看更多
疯言疯语
7楼-- · 2019-01-20 16:05

To use array in a string, you need to use {}:

$string = "{$couple['husband']} : {$couple['wife']} is my wife.";

Otherwise the parser cannot properly determine what you are trying to do.

查看更多
登录 后发表回答