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.
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))
来源:https://stackoverflow.com/questions/27742321/how-to-echo-element-of-associative-array-in-string