Passing PHP Variables to JavaScript

On this page we demonstrate and describe passing PHP variables containing simple data types to JavaScript. We demonstrate with string, boolean, and numeric values (i.e., scalar values).

To pass scalar data held in a PHP variable ($val) to a JavaScript variable, place the following in a JavaScript segment:

var val = "<?php echo $val ?>";

Notice the quotes around the PHP tags. This will result in a string value in JavaScript which you may need to convert for use in your scripts. If the PHP value is numeric, you don't need to include the quotes.

Example PHP Variables to JavaScript

Here we demonstrate with boolean, numeric, and string values assigned to PHP variables:

<?php
$bool = false;
$num = 3 + 4;
$str = "A string here";
?>

You could output them into JavaScript with the following:

<script type="text/javascript">
// boolean outputs "" if false, "1" if true
var bool = "<?php echo $bool ?>"; 

// numeric value, both with and without quotes
var num = <?php echo $num ?>; // 7
var str_num = "<?php echo $num ?>"; // "7" (a string)

var str = "<?php echo $str ?>"; // "A string here"
</script>

There are some conditions under which strings that are valid in PHP may generate errors in JavaScript when output using this approach. The PHP json_encode function can be used to resolve these problems as well as to preserve data type of booleans and numbers.

More on Passing Data from PHP to JavaScript

The approach presented here for passing simple data types will not work for more complex data such as arrays. Find out about passing single-level arrays from PHP to JavaScript and about the use of JavaScript Object Notation (JSON) to pass more complex data types.

Back to top