Forum Moderators: open
<html><head>
<title>test</title>
</head>
<body>
<?php
$t=array();
$t[]="zero";
$t[]="one";
?>
<script language="JavaScript"><!--
var message=<?php echo $t[0];?>;
document.write(message);
//-->
</script>
</body>
</html>
Perhaps you could fix my javascript to read the value from $t[0] and then print it.
If you want a Javascript variable that holds the string, "zero", then you need to get PHP to make sure that, this (including the quotes):
var mystring = "zero" appears, somewhere within <script> tags, on the page, as received by the client.
That is your department (PHP).
<script language="JavaScript"><!--
var message="<?php echo $t[0];?>";
document.write(message);
//-->
</script>
The PHP quotes indicate the value of the string to pass. When JS gets it, it looks more like a variable reference than a string to JS. Adding the quotes in the JS, as above, lets the script know the value is, indeed a string.
I want to get access to php array[$i] in javascript for loop.
Here is the code to illustrate the problem:
<body>
<?php
$t=array();
$t[]="zero";
$t[]="one";
?><script language="JavaScript"><!--
for(i=0; i<2; i++){
var message='<?php echo $t[i];?'>; //here is error
document.write(message);
}
//-->
</script>
</body>
<script language="JavaScript"><!--
for(i=0; i<=1; i++){
var message="<?php echo $t[i];?>"; //quotes outside PHP
document.write(message);
}
//-->
</script>
But that won't work, because it's a PHP array, and you are incrementing a Javascript variable. The solution is to use PHP to write the Javascript, like this:
<script language="JavaScript"><!--
<?php
for($i=0; $i<sizeof($t); $i++){
$message=$t[$i];
print("document.write(\"$message\");");
}
?>
//-->
</script>
Of course, in this case there is no need to use Javascript to write the array elements, because PHP can handle it just fine:
<?php
for($i=0; $i<sizeof($t); $i++){
$message=$t[$i];
print("$message<br />\n");
}
?>
Have fun, and you are encouraged to check out the PHP forum.