2

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.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76
Sheraz Ali
  • 315
  • 6
  • 19
  • **See also:** https://stackoverflow.com/questions/4738850/interpolation-double-quoted-string-of-associative-arrays-in-php – dreftymac Jul 27 '18 at 21:44
  • **See also:** https://stackoverflow.com/questions/8400018/syntax-error-unexpected-t-encapsed-and-whitespace-expecting-t-string-or-t-vari#13423474 – dreftymac Jul 27 '18 at 21:50

8 Answers8

2

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.';
Pupil
  • 23,834
  • 6
  • 44
  • 66
1

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

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
0

try this

 <?php $string = $couple['husband']." : ". $couple['wife']." is my wife."; 
  echo  $string//Brad : Angelina is my wife.
 ?>
Ankur Bhadania
  • 4,123
  • 1
  • 23
  • 38
0

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.

Erik
  • 3,598
  • 14
  • 29
0

You can simply do:

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

Or:

$string = $couple['husband'] . " : " . $couple['wife'] . " is my wife.";
Shitiz Garg
  • 604
  • 3
  • 7
0

Try like

$string = $couple['husband']." : ".$couple['wife']." is my wife.";
GautamD31
  • 28,552
  • 10
  • 64
  • 85
0

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

0
call_user_func_array('sprintf', array_merge(['%s : %s is my wife.'], $couple))
markcial
  • 9,041
  • 4
  • 31
  • 41