Knowledge

PHP Fundamentals: The Basics of Arrays

Published on January 10, 2014 under How-To, Web Development

The Basics of Arrays

In the modern scheme of server-side scripting, we’ve been amazed and awed by the innovations of online databases, XML feeds, and even JSON data sources. However, there is always the need to go back to the basics, to a more simpler way to temporarily store data. With that, I give you the array.

Now I was originally going to go into the basics of functions today, but a colleague I met on LinkedIn was asking me how he could augment premade PHP code so he could step through an array and manipulate individual pieces of data. Today I’ll answer his question, but also show you the basics of arrays, and why you might find them useful.

What is an array?

The best way I can describe an array is as a small, temporary database. Imagine you have a MySQL database table that only contains two columns. One is used as a primary key, the other to hold a piece of data. Setting one up in PHP is easy:

$blankArr = array();

$arrWithData = array("one", "two", "three");

It’s that simple. The first example is just a basic, empty array with no data. The second one is for an array loaded with three strings. The variable you decide to name the array is entirely up to you. If you wanted to see the anatomy of $arrWithData, it would look like this:

$arrWithData[
   0: one
   1: two
   2: three
]

The 0, 1, and 2 is your “primary key”. Unless you specify that key, PHP will just use numbers starting at 0 and go on. It’s not exactly certain the maximum you can put into an array, but many have gone as high as over 7000. Frankly, though, if you need that much, then it’s time to think bigger than an array.

Why use arrays?

Before we go further, you might be wondering why would you use this as opposed to other solutions? Granted it’s popular to use bigger technologies such as XML or JSON, but I tend to like arrays simply because of their temporary nature.

One big use I’ve had for them is when I need to pull data from multiple database tables and hang on to them to integrate together into one page. Unless you have a special trickery in code, usually you can only connect to one table at a time. Thus the need to store small amounts of data temporary to use moments later.

I wouldn’t suggest arrays with large amounts of data, but definitely short. One example are the categories on this page. I’ll store them in an array before pulling up the article content and other information needed.

Working with data in an array

Now I’ve already shown you how you can add data when you create an array, but there is a reason why I like to set up blank arrays first. Most of it is because I’ll need to add data much in how I pull data from a database.

So let’s say you want to add items to $blankArr, here’s the simplest form:

$blankArr[] = "red";
$blankArr[] = "yellow";
$blankArr[] = "blue";

This will end up with the array containing three entries, as shown:

$blankArr[
   0: red
   1: yellow
   2: blue
]

If we had put those three entries into $arrWithData, then they would have been following the original data put in, so their IDs would be 3, 4, and 5.

Now what if we want to break away from numeric IDs and instead put something else in, like the name of someone as the ID, and their age as the data:

$ageArray = array();

$ageArray["Tom"] = "26";
$ageArray["Dick"] = "35";
$ageArray["Harry"] = "24";

Not surprisingly, this is also the method to edit individual pieces of data in an array. So let’s say you want to change “yellow” to “green” in $blankArr:

$blankArr[1] = "green";

That’s it. Just like when you would query a database, you simply specify an ID and then what the new data is. Now what if we wanted to delete data from an array? The unset function allows you to clear out a whole array:

unset($blankArr);

You can also just delete individual pieces of data using unset:

unset($arrWithData[1]);

unset($ageArray["Dick"]);

Displaying data from an array

So we’ve now shown how to add, edit, and remove data in an array, but what about when you want to display the data? Or just pull a piece of data out for some purpose? You would do this no differently than you do with any normal variable, but you add in the brackets and the id of the item you want to pull.

Here’s an example:

$nameArr = array("Garfield", "Jon", "Odie", "Nermal");

echo "At " . $nameArr[1] . "'s house he has three pets: " . $nameArr[0] . ", " . $nameArr[2] . ", and " . $nameArr[3] . ".\n";

This would then come out as:

At Jon’s house he has three pets: Garfield, Odie, and Nermal.

There is also the print_r function, but I only find use for that when I need to test or troubleshoot an array. All it would do is display the results in a way that isn’t very useful for content layout. The above $nameArr would display like this:

print_r($nameArr);

Array ( [0] => Garfield [1] => Jon [2] => Odie [3] => Nermal )

Now, to answer the question

So now let’s say you want to shuffle through the entries of an array one by one for some reason. In the past I would have to count the number of items in the array using the count() function and then use a for loop to cycle through the items one by one. Here’s an example:

$arrOfNumbers = array(10, 20, 30, 40, 50, 60);

$arrayCount = count($arrOfNumbers) - 1;

for ($i = 0; $i <= $arrayCount; $i++) {
   $tempVar = $arrOfNumbers[$i];
   $arrOfNumbers[$i] = $tempVar + 5;
};

All I did there was cycle through each number and add 5 to them. The end result would be every entry now has 5 added to them. If you’re wondering why I subtracted 1 from $arrayCount, it’s because the array would start at 0 and end at 5, rather than start at 1 and end at 6. I needed $arrayCount to more reflect the last item in the array, not the actual number of items.

Thankfully with PHP5, we have an easier way to cycle through an array with the foreach loop. So let’s try that again:

foreach ($arrOfNumbers as $value) {
   $value = $value - 5;
};

All I’ve done now is subtract the 5 from each of the entries in $arrOfNumbers. Three lines of code to do the same that I did before. What happens is the foreach loop will cycle through the array. Each entry is temporarily pulled down as $value, and then you would do whatever you wish to the data. In this case I subtracted 5 from the integer.

You could also change the value of string data, like this:

$fruitBowl = array("apples", "oranges", "bananas");
$groceries = array("pears", "nectarines", "grapes");
$i = 0;

foreach ($fruitBowl as $items) {
   $groceries[$i] = $items;
   $i++;
};

The end result would be that the entries of $fruitBowl would now match those of $groceries. Basically this is a simplistic way to change out strings, but a more useful idea on this would be to cycle through a loop and print items out of an array. The next example also shows you how you can utilize the key as well:

$inventory = array(
   "Smartphones" => 24,
   "Tablets" => 10,
   "Laptops" => 18,
);

foreach ($inventory as $item => $amount) {
   echo $item . " = " . $amount . "<br>\n";
};

What you would end up with is a list of the items and their amounts, pulled from the array. Utilizing the key is a very handy way to get the most out of your array. You get two pieces of data for each entry as opposed to one, provided the keys still stay unique.

More to come

So let’s say you want to save more items than just a key and one piece of data. Are you stuck? Not at all. Next time, I’m going to show you arrays that can store more than the basic array.

For now, I have an example file I’ve made for you so you can see all that I’ve spoken of in action. Please feel free to comment or email me if you have questions.

Download example file Download the example file from this article

Tags: php fundamentals, php, array, data

comments powered by Disqus