如何在字符串中回显关联数组的元素


How to echo element of associative array in string?

我知道这是一个非常基本的问题,但我必须问。

我有一个关联数组,假设它是:

$couple = 数组('丈夫' => '

布拉德', '妻子' => '安吉丽娜'); 

现在,我想在字符串中打印丈夫的名字。有很多方法,但我想这样做,但它给出了 html 错误

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

如果我对反斜杠使用了错误的语法,请纠正我。

你的语法是正确的。

但是,您仍然可以更喜欢单引号而不是双引号。

因为,由于变量插值,双引号有点慢。

(解析双引号内的变量,而不是单引号的情况。

优化和更干净的代码版本:

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

使用输出格式化字符串函数,如 printf

<?php printf("%s : %s is my wife.", $couple['husband'], $couple['wife']); ?> 

如果要将输出存储在变量中,则必须使用 sprintf .

查看此演示:http://codepad.org/kkgvvg4D

试试这个

 <?php $string = $couple['husband']." : ". $couple['wife']." is my wife."; 
  echo  $string//Brad : Angelina is my wife.
 ?>

要在字符串中使用数组,您需要使用 {}:

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

否则,解析器无法正确确定您要执行的操作。

你可以简单地做:

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

或:

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

尝试喜欢

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

查看解决方案 -

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

如您所见,如果您在双 qoutes 中使用整个字符串,则必须删除单引号和反斜杠。

更好的方法是——

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

call_user_func_array('sprintf', array_merge(['%s : %s is my wife.'], $couple))