DEV Community

Supun Kavinda
Supun Kavinda

Posted on • Originally published at groups.hyvor.com

4 1

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.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

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!

Image of PulumiUP 2025

Explore What’s Next in DevOps, IaC, and Security

Join us for demos, and learn trends, best practices, and lessons learned in Platform Engineering & DevOps, Cloud and IaC, and Security.

Save Your Spot

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay