By Andrew Smith

I will have something like this on one of the pages in the website:

Each of those dropdown lists has the 190 language codes I mentioned in the previous post. It may not sound like a lot but 1900 <option> values really is a lot of HTML. It’s very easy to generate it all in PHP (one loop basically) but the result still has to be pulled over the internet, and suck up my bandwidth.

I had to think about this one for a bit, but I came up with a decent solution.

In my PHP loop I create two javascript arrays: one for visible name and one for value. I also have ten sets of dropdowns printed as HTML, but with the dropdown lists empty.

Then I write some javascript that will onload populate all the dropdown lists with all the names and values from the arrays.

This made the HTML sent to the browser probably 90% smaller, which made me very happy.

Just because it’s funny, here’s what some the php code looks like, I’m glad noone else will be working with me on this so I won’t have to explain it :)

  $languages = array();
  for ( $rowNum = 0; ($row = mysql_fetch_row($result)) != FALSE; $rowNum++)
    $languages[$row[0]] = $row[1];
    <script type="text/javascript">
    function contentOnLoad()
      var languageCodes = new Array(<?php 
  # make the PHP array a Javascript array
  $firstElement = TRUE;
  foreach ($languages as $code => $name)
    if ($firstElement)
      $firstElement = FALSE;
      echo ",";

    echo "'" . $code . "'";

That’s PHP, HTML, and JS all in one, still cracks me up :)