-1

how to add a javascript code correctly within a php code? I tried to do this with the code below, but I get the error:

Parse error: syntax error, unexpected 'text' (T_STRING), expecting ',' or ';'

<?php
$myImagesList = array (
'image1.png' ,
'image2.png' ,
'image3.png' 
);

shuffle ($myImagesList);
echo '<div style = "background: #0600ff" class = "div02">';
for ($i=0; $i<5; $i++) {
    if ($i < 5) {
        echo '' . $myImagesList[$i] . '';
    }
    if ($i == 5) {
       echo '</div>';
       echo ' <script type='text/javascript'>
var cpmstar_pid = 45265;
document.writeln('<SCR' + 'IPT language='Javascript' src='' + (document.location.protocol=='https:'?'//server':'//cdn') + '.cpmstar.com/cached/js/feedback_v101.pack.js'></SCR' + 'IPT>');
</script> ';
        echo '<div style = "background: #0600ff" class = "div02">';
     }  
     if ($i > 5) {
        echo '' . $myImagesList[$i] . '';
      }
  }
 echo '</div>';
?>
  • You have a for loop condition `$i<5`, then inside the loop you test if `$i == 5` so that'll never be true. Then you test if `$i > 5` which won't ever happen either. – nnnnnn Jul 11 '16 at 03:03
  • You should accept some of the answers people have offered otherwise you will find that people will stop answering your questions. – Rasclatt Jul 11 '16 at 03:18

1 Answers1

0

The issue is with the single quotes you are using with the script tag. You can use the heredoc syntax to write the JavaScript out with PHP.

echo <<< SCRIPT_BLOCK
<script>
var cpmstar_pid = 45265;
document.writeln('<SCR' + 'IPT language='Javascript' src='' + (document.location.protocol=='https:'?'//server':'//cdn') + '.cpmstar.com/cached/js/feedback_v101.pack.js'></SCR' + 'IPT>');
</script>
SCRIPT_BLOCK;
user2182349
  • 9,569
  • 3
  • 29
  • 41