LAMP Tutorials
Lamp Tutorials Contact CrackFeed

Introduction to PHP associative arrays

Part 3 of PHP Arrays Series

Authored on: June 22, 2011 by Jeffery Dilegge

Digg this tutorial!

Please support Crackfeed with a small donation.

Back to PHP Tutorials

Previous in series: Introduction to php numeric arrays.


As I discussed in my last PHP tutorial on numeric arrays in PHP, a PHP array is a sort of data map or sort of pseudo-database that stores data along with keys that are used to classify the data. Essentially, an array is a variable capable of containing multiple keys and values. In a numeric array, teh keys are simply numeric keys. Today I am discussing PHP associative arrays, these use strings as keys. Using a string for a key makes it easier to categorize your data and easier to fetch specific data without having to remember what number contains what data.


<?php
$foods = array('fruit'=>'apple','meat'=>'chicken','veggy'=>'carrot','fatty'=>'twinky');
?>

As you see with the above example, I have created an associative array that contains types foods. Notice the keys? The keys are strings that act as bookmarks within the array, allowing you fast and easy access to specific data within the array. Note that arrays are case sensitive. So if your key is named "fruit", you cannot call it with "Fruit". You can use strings with associative arrays or you can use numbers. Let's say that I want to get the value of the key named "meat". I do not have to loop through anything and I do not have to remember what the id is for that column in the array. I just refer to it as "meat":


<?php
echo $foods['meat'];
?>

That snippet will display the word "chicken". Pretty simple. Unlike the numeric arrays, I have to enclose the keyname inside of quotes. Single quotes or double quotes, it does not matter. I prefer single quotes becuase they look nicer. Let's say that you want to grab all of the data from the accociative array. Here is one example:


<?php
$foods = array('fruit'=>'apple','meat'=>'chicken','veggy'=>'carrot','fatty'=>'twinky');
foreach ($foods as $key=>$value) {
	echo 'A ' . $value . ' is a type of ' . $key . '
'; } ?>

Here, I am taking my array, $foods, and separating the keys from the values, in a sense, prior to looping through them. Within the loop I can specify the key and / or the value. You can call them multiple times or just one time, there is no limit.


<?php
$foods = array('fruit'=>'apples','meat'=>'chicken','veggies'=>'carrot','fats'=>'twinky');
foreach ($foods as $key=>$value) {
	if ($key != 'fats') {
		echo 'I like to eat ' . $value . '!
'; } } ?>

but more efficient is:

<?php
$foods = array('fruit'=>'apples','meat'=>'chicken','veggies'=>'carrot','fats'=>'twinky');

unset($foods['fats']); // This removes the fat like a Foreman grill!

foreach ($foods as $key=>$value) {
	echo 'I like to eat ' . $value . '!
'; } ?>

You can do just about anything to the data within your loop. Here, I said "I like to eat [food here]". However, since I do not prefer super fatty foods I excluded the fatty food by referencing the key "fats".

Now that you have a basic understanding of associative arrays, here is the reason we use them. The uses are plentiful. I use them for databases when I do not want too much weight on my databases. I also use them in order to pass data around from script to script without usign a ton of separate variables or sessions.

  • Great for making small temporary databases.
  • Great for minimizing variable usage.
  • Great for passing data from script to script.
  • Great for minimizing the number of columns used in a SQL database.
  • Great for confusing those new to PHP.

Take Onlyseek.com for example. Here is a site that I coded for a client that cross references a lot of data. I hate using MySQL JOINs and I hate excessive looping. So, to counter this I have a cron script that takes data that is not updated as often as others and it gathers all of user's info like friends and friends of friends and sorts them into arrays. It automatically groups the data, sorts the data and all of that jazz. So, when BillyBobJoe reloads his profile over and over because he has OCD; though he is not flooding the database with queries as he does this. A php function grabs the data needed to formulate most of his profile from a pair of arrays from a PHP file that the cron job generated for me. This reduced potential RAM usage by about 60% and the site can handle a lot of users at one time.


Next I will talk about multidimensional arrays. These are arrays that are truly useful. A multidimensional array is a set of arrays within an array. This allows us index data efficiently in a short term solution to using a database. Multidimensional arrays can be confusing to some at first, but once you understand them, you see they are simple to handle.


Next in series: Introduction to php multidimensional arrays.



Other tutorials in this series:

First in series: Introduction to php arrays.

Third in series: Introduction to php associative arrays.


Links Directory | Jeffery Dilegge