7

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 ?

5 Answers 5

16

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>
Sign up to request clarification or add additional context in comments.

1 Comment

good answer,a full php tag would have been so damn cooler than the short tags though(on line 7).
3

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/

2 Comments

It's nicer: echo "<script type='text/javascript'>\n"; echo "var js_array = " . json_encode($php_array) . "\n"; # .....rest of JavaScript..... echo "</script>\n";
No need for the $key value, since an JS array is not a hashmap. Just use js_array.push($value).
2

JSON is your choice, since some PHP 5.x version, PHP contains a function json_encode().

<script type="text/javascript">
var arr = <?php echo json_encode($php_array); ?>
</script>

As usual, some nice guys wrote json_encode() functions for older PHP version, checkout the comments on php.net.

Comments

1

The array in your PHP needs to be exposed to JavaScript in some way. If you want the array available to JS on the initial page load, you might do it like this:

<script type="text/javascript">
    myJSArray = <?php echo function_that_generates_array_in_js_syntax($myPHPArray); ?>;
</script>

If the variable doesn't need to be created on the initial page load, you can do something similar, but use an AJAX call. Simply have your PHP script respond with the array formatted for JS, and store the result of the call in your JS variable.

Comments

1

Variant on the PHP to JS without json extension, using join / implode and no loop construct:

<?php
$array= array('one','two','three');
$js_array= '["'. join('","', $array) .'"]';
?>
<script type="text/javascript">
var js_array= <?php echo $js_array;?>;
alert(js_array);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.