-1

I am learning PHP, and I want to output a PHP variable in between single quotes, something like this:

 $var1 = 'Text here';
 $var2 = $var1;

 echo $var2;

The output of $var2 should be:

 'Text here' 

(including the single quotes).

Does someone know the best way how to do this?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • In addition of Praveen's answer, I suggest the use of escape characters as explained [here](https://stackoverflow.com/questions/7999148/escaping-quotation-marks-in-php) – Nicola Elia Aug 09 '18 at 08:32

1 Answers1

3

You cannot just like that add a string. You need to enclose them in a string first.

$var1 = "'Text here'"; // Enclose this way.
$var2 = $var1;

echo $var2;

In your understanding, using the following code will give you an error.

$var = Hello World; // Error

In normal ways, a string can be defined by:

$var = "Hello World"; // or
$var = 'Hello World';

If you need to include quotes, you can also use escape characters. See Escaping quotation marks in PHP.

$var = "Hello \"Real\" World!";

And in your case, it could be:

$var1 = '\'Text here\'';

Another interesting way is:

$var1 = 'Text here';
$var2 = "'$var1'";
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252