Jump to content

Need help please


Jokersnl93

Recommended Posts

<!DOCTYPE html>
<html>
<body>

<?php
$array=array(1,2,3);



?>


<script>
for (i=0;i<3;i++)
{
 
let y= "<?php echo $array[i] ?>";
document.write(y);
}




</script>

</body>
</html>

can u tell me why i doesnt print anything from array ? but if a remove loop and  swrite $array[0] it prints 1, but if i write let i=0;
$array;
it prints nothing why ? they are same logic

Link to comment
Share on other sites

PHP runs on the server. - Javascript runs on the client.

On completion of the PHP it sends the page to the client where the javascript runs.

At the time you "echo $array;" the js variable "i" does not yet exist. (Error thrown if turn on error reporting)

By the time the javascript runs "$array" no longer exists.

  • Like 1
Link to comment
Share on other sites

<!DOCTYPE html>
<html>
<body>

<script>
<?php echo 'const array = ["one", "two", "three"];'.PHP_EOL; ?>
for (i=0;i<3;i++)
{
document.write(array[i]);
document.write('<br>');
}
</script>

</body>
</html>

your logic needs to change. use php to dynamically author JavaScript code or json/ajax to get values from php scripts. Barand explains the why.

Link to comment
Share on other sites

Because you are trying to use the javascript variable "i" inside the PHP code. Javascript is a client side processor and PHP is a server side processor so when the browser gets the file the PHP will already be processed which will give an error as i is undefined in the PHP code.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.