How to Set PHP Variable in JavaScript With Example

To Set PHP Variable in JavaScript, we need to define a JS variable and assign a PHP value using a PHP tag with single or double quotes.

How to Set PHP Variable in JavaScript With Example

Most of the time you have to set PHP variable value in JavaScript. If there is only a simple variable like a string or any integer then you can simply echo on the JS variable with a PHP tag.

For example, if you have a string value on the PHP variable and want to assign it and console it on JS.

Output:

Lorem ipsum dolor sit amet

If you have any array value in PHP and you want to get that value on the same JavaScript variable then,

Output on Console:

(3) [“Lorem”, “ipsum”, Array(2)]

0: “Lorem”

1: “ipsum”

2: (2) [“dolor”, “amet”]

Complete Example to Set PHP Variable in JavaScript

Output:

How to Set PHP Variable in JavaScript With Example
Example of accessing PHP variables in JavaScript

Here is a complete example, How to define PHP variables in JavaScript.

Pass PHP Variable as Parameter in JavaScript Function

Output:

Alert 10

In this example Pass PHP Variable as Parameter in JavaScript Function,

  • First, we define a PHP integer and then we create a JS function and
  • Take the PHP variable on our JS variable.
  • Then we call that function with the JS variable as a parameter, Which alerts the addition of numbers.

I think this is the complete guide about accessing PHP variables in JavaScript and also set PHP variable value to JS variable.

We also use parseInt() to convert string to integer in JS. You also read know more from here https://www.w3schools.com/jsref/jsref_parseint.asp

Also Check and Run Live on https://phpcoder.tech/php-online-editor/

Also Check:

Happy Coding..!

Was this article helpful?
YesNo
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP.
Posts created 189

2 thoughts on “How to Set PHP Variable in JavaScript With Example

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top