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.

2

8 Answers 8

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.';
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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

Comments

0

try this

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

Comments

0

You can simply do:

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

Or:

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

Comments

0

Try like

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.