How to Pass PHP Array to JavaScript Function

The json_encode() function in PHP provides an easy way to pass an array to JavaScript. Using json_encode() function, you can pass both single dimentional and multidimentional array to the JavaScript function.

The following example code shows you how to pass PHP array to JavaScript using json_encode() function.

The $phpArray variable holds a multidimensional PHP array which needs to pass to JavaScript.

<?php
$phpArray 
= array(
    array(
'name'=>'John Doe''email'=>'john@gmail.com'),
    array(
'name'=>'Merry Moe''email'=>'merry@gmail.com')
);
?>

The PHP json_encode() function is used to pass array to JavaScript function.

getUserInfo(<?php echo json_encode($phpArray); ?>)

Now the PHP array can be accessed as a JavaScript object and you can use it in the JavaScript code.

function getUserInfo(userObj){
    alert(userObj[0].name);
}

1 Comment

  1. Raihan Said...

Leave a reply

keyboard_double_arrow_up