Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

if i have an associative array in php.

Say, in the same view, i have $params array:

$parameters = array(
   'parameter1'=>'value1',
   'parameter2'=>'value2
);

Is there any way or php function or even javascript function to convert the php array to javascript array? in such a way that if we have the converted array, jsParameters, you'd be able to access it's fields and values like :

console.log(jsParameters.parameter1);
console.log(jsParameters.parameter2);

that will output, 'value1' and 'value2'. Is there a way? many Thanks!

share|improve this question

3 Answers 3

up vote 3 down vote accepted

Use json_encode:

console.log(<?php echo json_encode($parameters); ?>);
share|improve this answer

You should be able to call json_encode on the array, and echo that back to your application.

Check out the docs here

share|improve this answer

Use json_encode:

echo json_encode($parameters);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.