How to convert PHP array to JavaScript array?

Converting PHP arrays to JavaScript arrays is essential when passing server-side data to client-side scripts. PHP's json_encode() function provides a reliable way to achieve this conversion for both single and multidimensional arrays.

Syntax

// PHP side
$phpArray = array('value1', 'value2');

// JavaScript side
<script>
var jsArray = <?php echo json_encode($phpArray); ?>;
</script>

Example: Converting Simple PHP Array

Let's start with a simple PHP array containing user information:

<?php
$myArr = array('Amit', 'amit@example.com');
?>

<script>
var arr = <?php echo json_encode($myArr); ?>;
console.log(arr);        // Output: ["Amit", "amit@example.com"]
console.log(arr[0]);     // Output: "Amit"
console.log(arr[1]);     // Output: "amit@example.com"
</script>

Example: Multidimensional Array Conversion

<?php
$users = array(
    array('name' => 'John', 'email' => 'john@example.com'),
    array('name' => 'Jane', 'email' => 'jane@example.com')
);
?>

<script>
var userArray = <?php echo json_encode($users); ?>;
console.log(userArray[0].name);   // Output: "John"
console.log(userArray[1].email);  // Output: "jane@example.com"
</script>

Example: Associative Array to JavaScript Object

<?php
$person = array(
    'firstName' => 'Alice',
    'lastName' => 'Johnson',
    'age' => 30
);
?>

<script>
var personObj = <?php echo json_encode($person); ?>;
console.log(personObj.firstName);  // Output: "Alice"
console.log(personObj.age);        // Output: 30
</script>

Key Points

PHP Array Type JavaScript Result Access Method
Indexed Array Array arr[index]
Associative Array Object obj.property
Multidimensional Nested Array/Object arr[i][j] or obj.prop.subprop

Important Considerations

Always ensure your PHP data is properly sanitized before using json_encode(), especially when dealing with user input. The function automatically handles special characters and ensures valid JavaScript syntax.

Conclusion

Use json_encode() to seamlessly convert PHP arrays to JavaScript. This method works for all array types and maintains data structure integrity across server-client boundaries.

Updated on: 2026-03-15T23:18:59+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements