Posts Tagged ‘arrays’

In this tutorial I will be giving a basic introduction into PHP’s arrays. I will discuss how PHP implements them, how they differ and are similar to other languages, and basic use and functionality. Before you start learning, you should be familiar with the following

  • Basic PHP syntax
  • Variable use
  • Basic programming concepts (if statements, looping, etc.)

Basics

PHP arrays behave much like Vectors from C++, Lists from C#, Hash tables, associative arrays, etc. the syntax for creating one is very simple. There is a PHP function called array() which will return the array you would like based on what you specify in the argument list. Consider the following

 

$array1 = array();//this will create an empty array.

$array2 = array("item1", "item2", "item3");//this will create a numeric zero based array
echo $array2[1];//Output: item1

//the array function also supports setting up your own kay value pairs.
$array3 = array("key1" => "value1",  "key2", "value2");//this is an example if an associative array
echo $array3['key1'];//Output: value1

Pretty easy right? The key difference between the first 2 arrays and the last array is the keys you use to extract the values in the array. The first two are known as numeric arrays, since they use numeric keys (or in PHP terms, offsets). The last array used string keys, and is known as an associative array. Now you may be wondering when you would want to use one type versus the other. Well obviously this depends entirely on the context of your program, but I will give some examples of when one may be more useful than the other.

Lets say we have an array of all 50 states, and their capitals. Now we could use a numeric array, but then we, as the programmer, would have to remember which position each individual capitol is when we needed to use it. However, with an associative array, we can use the keys as the state name, and the values as the capitol. This makes it much easier to get a specific states capitol because we won’t have to remember or look back to see where, say, Connecticut’s capitol is located in the array. Consider the following

//numeric array
$capitols = array("Hartford", "Albany", ...etc);//this would be a numeric array

echo "The capitol of North Dakota is: " . $capitols[??];// hmm which offset is it? There are so many I don't quite remember and have to look it up in the arrays definition

//or we could do this
$capitols = array("Connecticut" => "Hartford", "New York" => "Albany", ... etc.);//

echo "The capitol of Tennessee is: " . $capitols['Tennessee'];//Now there is no doubt as to where the capitol of Tennessee is located in the array

Adding/Updating our array

Adding things to a PHP array is even simpler than making one. There are a few different ways of doing this. The most basic way is tothe use the square bracker ([]) operator with a new key and some value. Consider the following


$numeric_array = array("value0", "value1");
$numeric_array[2] = "value2";
//we dont actually need to add them in order. The following is valid and will execute
$numeric_array[17] = "value3";

$associative_array = array("key0" => "value0", "key1"=> "value1");
$associative_array['key2'] = "value2";

Easy peasy! Now there is also a third way to add things to an array. The syntax is to use empty square brackets along with the assignment operator. This syntax is mostly used with numeric arrays, because it adds the value to the next available numeric offset. Consider the following

$numeric_array = array("value0", "value1");
$numeric_array[] = "value2";//value2 is set to the value of $numeric_array[2] since 2 is the next available offset.

You can use the above with an associative array, but it would add the value at the key 0 (assuming it is a pure associative array). This is perfectly valid code, but now instead of having an associative array, you have a hybrid array. There isn’t anything inherently wrong with this, and hybrid arrays certainly have their place, but in general it makes the most sense to use this syntax with numeric arrays.

 

Now what?

Well now that we have an array, what can we do with it. Besides the obvious use of arrays, PHP comes with a bunch of different functions and constructs that make using arrays awesome and very worthwhile. You should already know about for loops, but PHP also provides a foreach loop (like what Java or C# has) which can iterate through an array. The syntax is fairly simple. There are two types. The simplest type is as follows:

foreach($array as $value)

What this does is inside the for loops code block, $value takes on each different value in the array as the loop iterates though. So if our array had the values: value1, value2, value3, value4 then $value would contain value1 in the first iteration, then value2 in the second, and so on. The second type is the same and is as follows:

foreach($array as $key => $value)

As I said, this iterates through each value in the array in the order they were added, but also sets $key to each key at that specific value. For numeric arrays, $key would be 0, 1, 2, etc.. in order (assuming you have an ordered numeric array). This type is especially useful with associative arrays since you may not know the exact order of the array, but you need to do a different line of code depending on the key.

Now, I mentioned functions earlier, and you can look at the whole list of array functions that PHP provides here: http://php.net/manual/en/ref.array.php

 

The ones I find myself using the most I will discuss below. Make sure you read the manual entry for each function (Link provided) as there are quite a few code examples and notes about the usage of these functions

count($array): This function returns the size of the array provided in the argument list. Very useful for determining the size of an array that is build dynamically.

sort($array): This sorts an array from lowest to highest. If you have string values, they are sorted lexicograhically by default, but provides certain flags as an optional parameter which allows you to specifiy how it should sort the array (numerically, strings, etc.).

shuffle($array): This function randomizes the order of the array provided in the argument list. This function is very useful when you want to print or otherwise use the array you created in a random order.

in_array($needle, $haystack): This function looks through the array ($haystack) and returns whether or not the value specified ($needle) in inside of the array. This function is extremely useful, and I find myself using it all the time. An example of usage would be when you are trying to see if one variable is equal to one of any number of different values. Instead of using the equality operator (==) many times chained together with ors (||), you can put all the values you are testing in an array, and use the in_array function.

 

Now, this guide is a very simplistic introduction to PHP arrays, and there are many many more functions and uses for arrays. Perhaps I will write a more advanced tutorial on array usage at a later date.

Some useful links you may want to check out:

The list of PHP’s array functions: http://php.net/manual/en/ref.array.php
The PHP manual entry for arrays: http://php.net/manual/en/language.types.array.php
A Tizag.com tutorial on PHP arrays: http://www.tizag.com/phpT/arrays.php
A website for all things PHP. They have some of the best PHP help forms, and I am a staff member here:  http://www.phpfreaks.com