20

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?

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
user1448031
  • 2,172
  • 11
  • 44
  • 89
  • 3
    Duplicate/Similar question: http://stackoverflow.com/questions/5618925/convert-php-array-to-javascript + http://stackoverflow.com/questions/4885737/pass-a-php-array-to-a-javascript-function – ro ko Mar 17 '13 at 13:47
  • And http://stackoverflow.com/questions/10758471/pass-php-array-to-jquery-function –  Mar 17 '13 at 13:48

7 Answers7

53

Use json encode.

json_encode — Returns the JSON representation of a value

Example:

var arrayFromPHP = <?php echo json_encode($arr); ?>;
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
7

You need to use json_encode

var jQueryArray = <?php echo json_encode($phpArray); ?>;
sdespont
  • 13,915
  • 9
  • 56
  • 97
7

You could use the json_encode function:

var jQueryArray = <?php echo json_encode($phpArray); ?>;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

You can use json_encode

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

echo json_encode($arr);
?>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
SteveP
  • 18,840
  • 9
  • 47
  • 60
3

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 ...

Radiotrib
  • 629
  • 5
  • 8
2

It's not going to be a JQuery array, it's a javascript array (just to clarify since it's sounds like you're probably a noob). Set your JS array to this:

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

See php json_encode docs: http://php.net/manual/en/function.json-encode.php

flynn
  • 1,572
  • 2
  • 12
  • 26
-1

You can use Json or use foreach in HTML file

<?php foreach($phpArray as $key => $val): ?>
      jQueryArray[<?php echo $key; ?>] = <?php echo $val; ?>
<?php endforeach; ?>
Thomas
  • 503
  • 1
  • 12
  • 18