How to Set PHP Variable in JavaScript With Example

Bikash Panda
2 min readApr 17, 2021

--

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 a simple variable like a 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.

<?php
$nrmlString = ‘Lorem ipsum dolor sit amet’;
?>
<script type=”text/javascript”>
var normalText = ‘<?php echo $nrmlString; ?>’;
console.log(normalText);
</script>

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,

<?php
$stArray = array(‘Lorem’, ‘ipsum’, array(‘dolor’, ‘amet’));
?>
<script type=”text/javascript”>
var phpArray = <?php echo json_encode($stArray); ?>;
console.log(phpArray);
</script>

Output on Console:

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

0: “Lorem”

1: “ipsum”

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

Complete Example to Set PHP Variable in JavaScript

<?php

$nrmlString = ‘Lorem ipsum dolor sit amet’;
$stArray = array(‘Lorem’, ‘ipsum’, array(‘dolor’, ‘amet’));
?>
<script type=”text/javascript”>
var normalText = ‘<?php echo $nrmlString; ?>’;
console.log(normalText);
var phpArray = <?php echo json_encode($stArray); ?>;
console.log(phpArray);
</script>

Output:

Here is the complete example, How to define PHP variable in JavaScript.

Pass PHP Variable as Parameter in JavaScript Function

<?php
$nrmlString = 5;
?>
<script type=”text/javascript”>
var normalText = ‘<?php echo $nrmlString; ?>’;

function printaddition(userPHPNumber){
alert(parseInt(userPHPNumber)+5);
}
printaddition(normalText);
</script>

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 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/

Happy Coding..!

Originally published at https://phpcoder.tech on April 17, 2021.

--

--

Bikash Panda

I am a web application developer. FB Community: @mrpandatech, Twitter: @phpcodertech My PHP problem-solving site http://phpcoder.tech