Pass a PHP array to a JavaScript function

Pass a PHP array to a JavaScript function

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Passing PHP Arrays to JavaScript Functions Without json_encode

You cannot pass a raw PHP array variable directly into a JavaScript function call within an HTML template, even if you use short tags or heredoc syntax. The fundamental issue lies in how the browser interprets data versus how PHP processes it. When your code executes <script>drawChart(...) on the client side, the JavaScript engine expects valid JSON or string literals. If you simply echo a raw PHP array like <?php echo $day; ?>, the output is not a JSON object; it is a PHP-specific representation that the browser treats as an invalid syntax error or a malformed variable, causing your chart to fail immediately.

To fix this, you must serialize the PHP data into a format the browser understands before embedding it in the script tag. The standard solution is json_encode(). This function converts your PHP array into a JSON string, which can then be safely injected into your JavaScript arguments. However, there is a critical nuance regarding how that string interacts with the surrounding JavaScript code.

Consider the structure of your current call:

drawChart(600/50, '&lt;?php echo $day; ?&gt;', ...);

When PHP processes echo $day, it outputs something like [10, 20, 30]. If you do not wrap this output in quotes or treat it as a string variable within the JavaScript context, you are breaking the syntax of the function call.

Here is the corrected approach using json_encode:

<script>
    // Serialize PHP arrays to JSON strings
    var dayData = '<?php echo json_encode($day); ?>';
    var weekData = '<?php echo json_encode($week); ?>';
    var monthData = '<?php echo json_encode($month); ?>';
    var dateData = '<?php echo json_encode(createDatesArray(...)); ?>';

    // Pass the variables to your function
    drawChart(600/50, dayData, weekData, monthData, dateData);
</script>

By assigning the encoded strings to JavaScript variables first, you ensure that the data is treated as a string literal within the script environment. This prevents syntax errors related to commas or brackets appearing at unexpected places in the code stream. The json_encode function also handles escaping characters automatically, ensuring that if your array contains special characters like quotes or backslashes, they are properly neutralized for the browser.

Handling Null Values and Empty Arrays

A common pitfall arises when dealing with empty arrays or null values returned from your PHP logic. If $day is an empty array [], json_encode will output "[]". This is valid JSON and safe to pass to JavaScript. However, if a variable is uninitialized or null, json_encode(null) returns the string "null".

In your specific case, you are using a switch statement to populate arrays based on $au[$counter]->id. If a case matches but $au[$counter]->value is missing or null, the resulting array might contain null entries. When passed to JavaScript, these become null values in the JSON array. Your JavaScript function must be robust enough to handle this. If your chart library does not accept null values in the dataset, you should filter them out before encoding:

// Filter out null or empty values before encoding
$day = array_filter($day, function($item) { return $item !== null && $item !== ''; });
$week = array_filter($week, function($item) { return $item !== null && $item !== ''; });
$month = array_filter($month, function($item) { return $item !== null && $item !== ''; });

// Now safe to encode
drawChart(..., json_encode($day), ...);

Alternative: Inline JSON Encoding

While the variable assignment method is clean and readable, you can also encode directly inside the argument list. This approach reduces the number of lines but requires careful attention to spacing and readability.

<script>
    drawChart(600/50, 
        '<?php echo json_encode($day); ?>', 
        '<?php echo json_encode($week); ?>', 
        '<?php echo json_encode($month); ?>', 
        '<?php echo json_encode(createDatesArray(...)); ?>'
    );
</script>

This method is functionally identical but can make the code harder to debug if the output becomes complex. The variable assignment pattern allows you to inspect dayData in a debugger before passing it, which is often preferable during development.

Conclusion

The inability to pass raw PHP arrays directly stems from the separation between server-side execution and client-side interpretation. By using json_encode() to bridge this gap and ensuring that null values are handled appropriately, you can seamlessly transfer dynamic data structures from your PHP backend to your JavaScript frontend logic.

Our network