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 ?
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>
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With