Home » Php » PHP Ampersand in String

PHP Ampersand in String

Posted by: admin July 12, 2020 Leave a comment


I’m having a bit of a problem. I am trying to create an IRC bot, which has an ampersand in its password. However, I’m having trouble putting the ampersand in a string. For example…


$var = "g&abc123";

echo $var;


I believe this should print g&abc123. However it’s printing g.

I have tried this as well:

$arr = array("key" => "g&abc123");

This prints it correctly with the g&abc123, however when I say echo $arr['key']; it prints g again. Any help would be appreciated. I’m running PHP5.3.1.

EDIT: Also, I just noticed that if I use g&abc123&abc123 it prints g&abc123. Any suggestions?

How to&Answers:

I don’t have that issue in a console:

php > $d="g&abc123";
php > echo $d;

What environment are you printing the output to? It sounds like you are viewing it in a web browser, and the & is being interpreted as a malformed HTML entity. Try replacing the & symbol with the entity encoded version &amp;.


Look at the source code, it will be printing the correct code.

If you want it to print out correctly in HTML, then run htmlentities on it or make the & &amp;


View the web page source to make sure your variable contains the correct value.


You’re probably sending your output to a Web browser.

The correct way of doing it is

In HTML, XHTML and XML, the ampersand has a special meaning. It is used for character entities. You can think of it as an escape sequence of sorts.

For instance, in PHP, this would be illegal:

$variable = 'It's Friday';

This is because the apostrophe is interpreted by PHP as the end of your string, and the rest of your content looks like garbage.

Instead, you have to say:

$variable = 'It\'s Friday';

Similarly, in HTML and XHTML, you can’t say

<p> x<yz+3 </p>

This is because it would be interpreted as an element.

Instead, you’d have to say:

<p> x&lt;yz+3 </p>

Now, as you can see, the ampersand itself has a special meaning and, therefore, needs to be escaped as &. htmlspecialchars() will do it for you.