Populate Select Boxes using a Global Associative Array with PHP

The following post is being written because today I’ve been annoyed, very annoyed. I’ve been working on updates to a previous developers mini CRM system that I inherited, unfortunately. Basically, the customer wanted to amend the list of options that appear in a HTML select box, on pretty much every page. In this case, 24 pages.

Ok, easy job – or so I thought. If the previous developer hadn’t been a total mong this simple update would have taken a minute or so – simply update a common function, database or global array to repopulate the drop down list options. No luck in the least – the developer had hard coded each drop down into every page, using HTML – **** great! So I just spent close to 40 minutes wading through include files and HTML to make my changes – so unecessary.

So, what follows is a very simple method to have a common drop down list that will be included on any page you want, with the data stored in a global array (could be a database, but a global array is quickest:

The include, model or config file – simple an associative array that will be accessible throughout your application (lets call this file includes.php):

global $customer_types;
$customer_types = array("1"=>"Normal", "2"=>"Debtor", "3"=>"Dispute", "4"=>"Premium");

The page or view – simply loop through the associative array (as we defined it as a global variable earlier) using the key/value style:

include 'includes.php';
echo '<select name="myTypes">';

foreach ($customer_types as $key=>$value) {
    echo '<option value="'.$key.'">'.$value.'</option>';
}

echo '</select>';

… and there you have it, in a couple of lines code you have an select box that can be maintained from a single file and used on as many pages as required.

/slaps previous developer for making me waste 40 minutes unecessarily 🙂

Published by

Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

One thought on “Populate Select Boxes using a Global Associative Array with PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *