Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an array value from php to javascript?

Tags:

javascript

php

it was always a question for me that how can i use an array value in javascript while that array is defined in my php scripts

For example consider reading some values from a file and use it in javascript.

what's ur plan to do so ?

like image 290
Mac Taylor Avatar asked Feb 01 '10 21:02

Mac Taylor


2 Answers

You can use the json_encode function, to safely return a JSON object which you can use directly in JavaScript:

<?php
  $phpArray = array("foo", "bar", "baz");
  //....
?>

<script type="text/javascript">
var jsArray = <? echo json_encode($phpArray); ?>;
</script>

Outputs:

<script type="text/javascript">
var jsArray = ["foo","bar","baz"];
</script>
like image 143
Christian C. Salvadó Avatar answered Sep 20 '22 13:09

Christian C. Salvadó


Something like this?

<?php
  # create PHP array:
  $php_array = array("one", "two", "three");

  # "pass" php array to JS array:
  echo "<script language='JavaScript'>\n";
  echo "var js_array = new Array();\n";

  $ix = 0;
  foreach($php_array as $key => $value) {
     echo "js_array[$key] = $value;\n";
  }

  # Rest of JavaScript.....
  echo "</script>\n";
?>

And perhaps for more info:
http://www.scratch99.com/2008/03/creating-javascript-array-dynamically-from-php-array/

like image 31
Zyphrax Avatar answered Sep 21 '22 13:09

Zyphrax