Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you assign a PHP array to jQuery array? [duplicate]

I am unable to figure out how to assign PHP array to jQuery array?.

I want to do something like the following:

var jQueryArray = <?php $phpArray; ?>;

Can anyone tell me how I can do this?

like image 885
user1448031 Avatar asked Mar 17 '13 13:03

user1448031


5 Answers

Use json encode.

json_encode — Returns the JSON representation of a value

Example:

var arrayFromPHP = <?php echo json_encode($arr); ?>;
like image 74
dsgriffin Avatar answered Sep 22 '22 12:09

dsgriffin


You need to use json_encode

var jQueryArray = <?php echo json_encode($phpArray); ?>;
like image 21
sdespont Avatar answered Sep 24 '22 12:09

sdespont


You could use the json_encode function:

var jQueryArray = <?php echo json_encode($phpArray); ?>;
like image 24
Darin Dimitrov Avatar answered Sep 21 '22 12:09

Darin Dimitrov


You can use json_encode

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>
like image 40
SteveP Avatar answered Sep 24 '22 12:09

SteveP


Don't forget that PHP json_encode will only work on UTF8 encoded text ...

$jsonString = json_encode(array_map(utf8_encode, $rawArray));

would be a more universal solution I think, but I'm a bit tired so 'scuse any coding gaffs ...

like image 31
Radiotrib Avatar answered Sep 24 '22 12:09

Radiotrib