How to Pass a PHP Variable to JavaScript – Easy Way

For something seemingly so straight-forward, you would think that the information out there would be a bit better on this subject. Passing a variable from PHP to JavaScript is actually very easy! There are just a couple things you need to keep in mind and some ways to do it to ensure it actually works.

I find that putting the following code into the <head> section of my website is the most foolproof method:

That’s it! You just define the PHP variable first, then echo it into a basic JS variable declaration statement. I know there are lots of ways to define a JavaScript variable, but this is the one I find works in the most circumstances. I’m not an expert here, but most of the others seem to not work a lot of the time.

A few things to keep in mind for this:

1. The PHP variable needs to be defined before the JS one.
2. The JS variable needs to be defined before you actually use it anywhere. This seems obvious, but if you forget this fact and try to put this declaration into the footer of your site and then use it in the content, you’ll find it doesn’t work! That’s why I like to put this in the head section of my website. Or, if you were in WordPress or another CMS, make sure to place it in the header.php file of your active theme.

Additionally, you should be aware that if your variable is not a string and is instead a number, you would want to define it without the quotes around it, i.e.:

Hard to go wrong with any of this. There are of course more complicated ways to use this, but I’m not going to go into any of those here. Let me know if you have any problems!

About Brian Johnson

Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.

4 Comments on “How to Pass a PHP Variable to JavaScript – Easy Way”

    1. PHP is server-side and happens before the page is rendered, so no. But you could pass the JS variable as a URL parameter or something and go to a new page or refresh the current page to get it.

  1. Stumbled on this while looking for a package to convert php vars to js.

    No clue how old this article is…but. Please don’t follow this recommendation. The second your string contains a double quote, it will break. If you want to use other types you have a world of headaches.

    A better method is to json_encode the value before giving it to the js.

    1. That may be true, but for my purposes (and likely the purposes of most of the people here), we don’t need to worry about quotes being in our variables. Generally I’m just doing something quick and easy and don’t want to go through the trouble of encoding and doing other complicated things that really aren’t necessary for what I’m doing.

Leave a Reply

Your email address will not be published. Required fields are marked *