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