Skip to content
PHP Logo

What are the best practices for formatting PHP arrays to be compatible with JavaScript object literals?

When passing PHP arrays to JavaScript as object literals, it is important to format the arrays correctly to ensure compatibility. To do this, you can use the json_encode() function in PHP to convert the array into a JSON string, which can then be easily parsed by JavaScript as an object literal.

php
<?php
// Sample PHP array
$phpArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

// Convert PHP array to JSON string
$jsonString = json_encode($phpArray);

// Output JSON string
echo "var jsObject = " . $jsonString . ";";
?>