Skip to content Skip to sidebar Skip to footer

How To Use An Array Value From Php To Javascript?

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 fil

Solution 1:

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");
  //....?><scripttype="text/javascript">var jsArray = <?echo json_encode($phpArray); ?>;
</script>

Outputs:

<scripttype="text/javascript">var jsArray = ["foo","bar","baz"];
</script>

Solution 2:

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_arrayas$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/

Solution 3:

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

<scripttype="text/javascript">var arr = <?phpecho json_encode($php_array); ?></script>

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

Solution 4:

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:

<scripttype="text/javascript">
    myJSArray = <?phpecho 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.

Solution 5:

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) .'"]';
?><scripttype="text/javascript">var js_array= <?phpecho$js_array;?>;
alert(js_array);
</script>

Post a Comment for "How To Use An Array Value From Php To Javascript?"