Home » How to Set PHP Variable in JavaScript With Example

How to Set PHP Variable in JavaScript With Example

To Set PHP Variable in JavaScript, we define a JS variable and assign PHP value using 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 simple variable like string or any integer then you can simply echo on the JS variable with 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 access PHP variables in JavaScript

Here is the complete example, How to define PHP variable 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 JS variable as a parameter, Which alerts the addition of numbers.

I think this is the complete guide about access 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

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

  1. Pingback: 3 Great JSON Beautifiers to Make Your JSON Pretty - PHPCODER.TECH

  2. Pingback: Explain Different Parts of The URL With Example - PHPCODER.TECH

Leave a Reply

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