How to echo element of associative array in string?

谁都会走 提交于 2019-11-28 14:19:47

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.';

Using output formatting string function such as printf

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

If you want store the output in a variable, you have to use sprintf.

Checkout this DEMO: http://codepad.org/kkgvvg4D

try this

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

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.

You can simply do:

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

Or:

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

Try like

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

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.';

call_user_func_array('sprintf', array_merge(['%s : %s is my wife.'], $couple))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!