Jokersnl93 Posted September 9 Share Posted September 9 <!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 Quote Link to comment https://forums.phpfreaks.com/topic/323927-need-help-please/ Share on other sites More sharing options...
Barand Posted September 9 Share Posted September 9 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. 1 Quote Link to comment https://forums.phpfreaks.com/topic/323927-need-help-please/#findComment-1634941 Share on other sites More sharing options...
jodunno Posted September 9 Share Posted September 9 <!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. Quote Link to comment https://forums.phpfreaks.com/topic/323927-need-help-please/#findComment-1634957 Share on other sites More sharing options...
royalindigo Posted September 9 Share Posted September 9 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. Quote Link to comment https://forums.phpfreaks.com/topic/323927-need-help-please/#findComment-1634961 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.