title: Access a PHP array from JavaScript
body: <p>I have the following code where I declare a PHP array variable and inside a function, I put some data into the array. I also display buttons mapped to each index of the array that will show the data in the PHP array for that index number.</p>
  
  <p>When testing on a browser, I don't get the right answer. I checked the page source, it had code like <code>data_array = ["&lt;?php echo implode ('',Array); ?&gt;"];</code> instead of the text from the Array.</p>
  
  <p>What am I doing wrong and what should I do to get the correct output? (BTW, I tried to execute the same without declaring the function and it seemed to work, but I need a function for my work and can't take that approach).</p>
  
  <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  &lt;html lang="en"&gt;
      &lt;head&gt;
          &lt;title&gt;Example&lt;/title&gt;
  
          &lt;?php
              $giant_says = array();
  
              function display()  {
                  global $giant_says;
  
                  $giant_says[] = "&lt;a href='http://www.google.com'&gt;Google&lt;/a&gt;";
                  $giant_says[] = "Yahoo!";
                  $giant_says[] = "Bing";
  
                  echo "&lt;div id='content'&gt;";
                  echo $giant_says[0];
                  echo "&lt;/div&gt;&lt;br&gt;&lt;br&gt;";
  
                  $i = 0;
                  while($i &lt; count($giant_says))  {
                      echo "&lt;input type='button' value='".$i."' onClick=\"addtext(".$i.");return false;\"";
                      $i += 1;
                  }
              }
          ?&gt;
  
          &lt;script type="text/javascript"&gt;
            function addtext(index) {
                giantSays = ["&lt;?php echo implode ('","', $giant_says); ?&gt;"];
                document.getElementById('content').innerHTML = giantSays[index];
            }
          &lt;/script&gt;
      &lt;/head&gt;
  
      &lt;body&gt;
          &lt;?php
              display();
          ?&gt;
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>