DEV Community

Supun Kavinda
Supun Kavinda

Posted on • Originally published at groups.hyvor.com

How to create Javascript variables from PHP variables?

Sometimes, you may need to declare dynamic JS variables using PHP.

One thing you can do is to manually write the JS code as following.

var x = "<?php echo $name ?>";
Enter fullscreen mode Exit fullscreen mode

But, we can create a function to do this easily with a better data types support.

function phpVarsToJs($vars) {
    echo '<script>';
    foreach ($vars as $key => $val) {
        echo "var $key =";
        if (is_int($val)) echo $val;
        else if (is_bool($val)) echo $val ? 'true' : 'false';
        else if (is_string($val)) echo '"' . $val . '"';
        else if (is_array($val)) echo json_encode($val);
        echo ';';
    }
    echo '</script>';
}
Enter fullscreen mode Exit fullscreen mode

This function requires an PHP array, which contains key/value pairs which are the Javascript variable name and the value. Also, this function automaically creates Javascript variables according to the data type of the PHP variable.

PHP Arrays will be converted into JSON format. If you don't need the '<script>' tags, just remove those two echo statements.

Example

<?php
    require_once 'functions.php'; // assuming this includes our function
?>
<html>
<head>
    <title>My App</title>
</head>
<body>
    This is my app!

    <?php
        phpVarsToJs(array(
            'name' => 'John',
            'age' => 23,
            'meta' => [
                'height' => 168, // cm
                // and more ... 
            ]
        )); 
    ?>

</body>
Enter fullscreen mode Exit fullscreen mode

Thanks!

I previously published this post on PHP Group on my new website, Hyvor Groups.

Top comments (2)

Collapse
 
msamgan profile image
Mohammed Samgan Khan

nice article, but this will only work if we are using JS in the same PHP file. What if we include the js from some other file?

Collapse
 
supunkavinda profile image
Supun Kavinda

I think you are talking about adding some PHP variables into a Javascript file. For example, you need index.js to have some dynamic variables to be set with PHP.

If it is what you meant, you can include the js file and the JS file should contain PHP in it.

<?php include_once 'index.js'; ?>

This will execute the PHP code in it and echo the contents to the current PHP file. But, having PHP code inside a Javascript file is a mess, in my opinion.

If you need to use this approach, I would recommend adding those dynamic variables into your PHP file. You can use an include for this. Here's how I do that.

<?php include_once 'js-config.php' ?>

And, js-config.php will have something like:

<?php
    phpVarsToJs(array(
         'name' => 'John',
         'age' => 23,
         // ....
    )); 
?>

If you don't need the Javascript variables (or JSON data) on the page load, the best way is to fetch the data from the server using AJAX.

Thanks!