Understanding arrays is the first major milestone when learning how to code. An array is not an easy concept to grasp at first since an array has many values, or elements, and can be used in so many ways. Many functions return their results as an array. There is no way around it, if you want to learn how to code, be it in php, javascript or any other language, you will need to understand the array.
A common definition for an array is a list used to organize or group elements. This is, to some degree, an accurate definition. Arrays share many characteristics of a list, but list can only be used to organize items and arrays can do a bit more. A better definition would be that an array is a container where you can organize, group and store items. The big difference being that a container holds the actual items and a list only is a reference of the items. If I give you a list of my tools all you can do is reorganize the list for your own use, but if I give you a box with my tools you can reorganize, borrow, add a new one and then give the box back to me with the modifications you made.
There are two types of arrays: Numerical Arrays (also referred to as Indexed Arrays) and Associative Arrays. However, php does not treat the two types any differently, as far as php is concerned they are both simply arrays.
There are also Multidimensional Arrays, which are arrays, either numerical or associative that have arrays as values (in other words multiple values).
At first glance an array is very similar to a variable, we identify it with a $ and give it a name.
$variableName
It is when assigning an array’s values that things change. PHP is very flexible and you do not need to declare a variable as an array before using it but we do need to use the correct syntax. The method for defining an array is with the following syntax:
$arrayName = array ("value-1″,"value-2″,"value-3″)
You can also set each array item individually by using the square bracket syntax:
$arrayName[] = "value-1"; $arrayName[] = "value-2"; $arrayName[] = "value-3";
Both methods will result in the same array $arrayName containing the 3 set values. You can even mix the two methods:
$arrayName = array ("value-1″,"value-2″,"value-3″);
$arrayName[] = "value-4";
$arrayName[] = "value-5";
This will result in the $arrayName array having 5 indexed values value-1 to value-5.
note: You could also use the array_push() function to add elements to an array.
note: array values can be strings, integers or arrays.
In an array each value gets a unique index, or key assigned to it. In order to return a specific value from the array you need to identify the element by its key. The format of the index key is what defines the type of array. In a numerical array the key is defined by a unique numeric id. If no key value is defined when assigning the array values then php will default to a numerical array. In the previous example we created a numerical array. To get a better understanding let’s look inside this array.
We can view an array’s contents by using the print_r() function. This function is very useful when debugging arrays since it lets you look inside an array’s structure and see it’s element’s key/value relationships. If we run print_r on the array we have just created it will output:
note: wrap the output of print_r with <pre> tags for readable formating
Array
(
[0] => value-1
[1] => value-2
[2] => value-3
[3] => value-4
[4] => value-5
)
The index key is displayed in the square bracket [3] and the corresponding value is displayed after the arrow =>. Examine the array output and you will notice two important factors:
Now that we know the index key that corresponds to the value we want to retrieve from the array we can use the key to isolate the element we want. We know that “value-2″ corresponds to index key 3, and we can echo this value with the following syntax:
echo $arrayName[3]
In an associative array the index key is defined by a string rather than an integer. This is a very powerful feature since this will allow us to associate a descriptive key to identify the value as opposed to a non-descriptive number. Associative arrays are set by assigning key => value pairs for each array element. We can use the array() or square bracket format to define an associative array:
$arrayName = array("key1" => "value-1", "key2" => "value-2");
// or use square braket sytax
$arrayName["key3"] = "value-3";
$arrayName["key4"] = "value-4";
Notice the difference when we output the array structure with print_r, the keys are the values that we defined and not numerical:
Array
(
[key1] => value-1
[key2] => value-2
[key3] => value-3
[key4] => value-4
)
We access the array values in the same way we do with numerical arrays. To return the value of the array element with the key of "key2" we would:
echo $arrayName["key2"];
You can see how this can be very useful if we use descriptive keys:
$dinner["drink"] = "red wine"; $dinner["food"] = "steak"; $dinner["desert"] = "apple pie";
note: you can mix numeric and associative keys in the same array.
We have seen how to return individual values from an array. However, there will be occasions where you will want to go through the structure of an array to interact with the array values. The foreach() loop is the most common method for iterating through an array. It works like a loop that will go through the array and provides a method for you to extract the value or the key => value pair for each array element. The syntax for the foreach function is:
foreach (array as $value) {
...
}
Or for returning the key and the value:
foreach (array as $key => $value){
...
}
Let’s see how we can use an array with the foreach loop to generate a link menu. First we create an array to store the information for out menu. The info we need is the link text and the link url. For this we will use an associative array and take advantage of the key value as the link text.
$myMenu["home"] = "home.html"; $myMenu["about"] = "pages/about-us.html"; $myMenu["services"] = "internet/services.html"; $myMenu["contact"] = "form/contact.html";
Now we can use the foreach loop to build the menu output:
foreach($myMenu as $key => $value){
$output .= "<a href=\"$value\">$key</a><br />\n";
}
echo $output;
This will output our menu as:
<a href="home.html">home</a><br /> <a href="pages/about-us.html">about</a><br /> <a href="internet/services.html">services</a><br /> <a href="form/contact.html">contact</a><br />
So far we have worked with simple arrays where there is one key corresponding to a single ‘value’ for each array element. However, what happens if we need more than one key=>value pair per element? We can handle this by using an array as the value for an element so that one key can have multiple values based on a second key layer, or dimension. Like those cool boxes that you open and there is another box inside it.
Expanding on the previous link menu example we can modify the array to include additional fields for our menu.
$myMenu["home"] = array("url" => "home.html", "text" => "Home Page");
$myMenu["about"] = array("url" => "pages/about-us.html", "text" => "About Us");
$myMenu["services"] = array("url" => "internet/services.html", "text" => "Our Services");
$myMenu["contact"] = array("url" => "form/contact.html", "text" => "Contact Us");
To get a clear view of how this array is structured lets look at it with print_r():
Array
(
[home] => Array
(
[url] => home.html
1 => Home Page
)
[about] => Array
(
[url] => pages/about-us.html
1 => About Us
)
[services] => Array
(
[url] => internet/services.html
1 => Our Services
)
[contact] => Array
(
[url] => form/contact.html
1 => Contact Us
)
)
Notice that there are multiple values available for each top level element. We can access the values within the array directly by including the subsequent index key to the array name:
echo "<a href=\"{$myMenu['home']['url']}\" >{$myMenu['home']['text']} </a>";
Notice that we are using the {} around our array, this is the syntax for referencing a complex variable and is referred to as "complex (curly) syntax".
We can iterate through a multidimensional array using the same method as we did with the standard arrays, using the foreach () loop and adding additional loops for each level we want to reach in the array:
foreach($myMenu as $key => $val){
foreach($val as $k => $v){
$url = $k;
$link = $v;
}
$output .= "<a href=\"$url\" title=\"$key\" id=\"$key\">$link</a><br />\n";
}
echo $output;
The output will be:
<a href="text" title="home" id="home">Home Page</a><br /> <a href="text" title="about" id="about">About Us</a><br /> <a href="text" title="services" id="services">Our Services</a><br /> <a href="text" title="contact" id="contact">Contact Us</a><br />
As you can see we were successfully able to include additional data to our array.
PHP has a full set of tools that allow you to manipulate and interact with arrays in virtually any way that is needed. Here are some common functions you should know
Sorting Arrays: PHP has many functions for sorting arrays, the most common are the to sort by ‘value’, or sorting by key.
// sort by value asort($arrayName); // sort by key ksort($arrayName);
note: you can also use the sort() function, but this will not retain the key association to the value.
Checking if a variable is an array: Use is_array() to see if a variable is an array.
if(is_array($arrayName){ ... }
Checking if a value is in an arrray: Use in_array() to see if a value is in an array.
if(in_array("value", $arrayName)){ ... }
How many elements in an array: Use count() to return the number of elements in an array.
echo count($arrayName);
How many elements in a multidimensional array: Use the second parameter for count() to enter COUNT_RECURSIVE mode.
echo count($arrayName, 1);
There are many more, be sure to check out the php documentation on array functions for a complete list of the available functions.
Great piece on PHP arrays! I’ve coded in a number of languages, and still find that PHP handles arrays best of all. The array functions its core comes with are fantastic.
Yeah, the more I use arrays the more I love them..and the way php handles arrays is great. I had a heck of a time figuring out how to work with them at first but now I think every script will use at least one array
Still learning PHP, arrays may come later. Familiar enough with them to be dangerous, so this will be great information later. Thanks!
Thank you for this. PHP arrays is one of those things I aim to master, and which I’ve figured out is absolutely crucial to my budding PHP skills, but they always throw me for a loop. This is an excellent writeup that I know I’ll bookmark and revisit often!
thanks much Shane!
mary
I really wish this article would have been around when I started learning php, arrays took me a while to get the hang of.
I think it really takes a while using php until you realize how powerful and useful they are, from error reporting/displaying, to handling xml feeds, and results from MySQL.
Also, I really laughed when Mary said ‘they always throw her for a loop’, so many programming puns could be made, I just don’t know where to start. You know I love you Mary!
Great article Shane
Great work, Shane!
I did want to point out, however, that there’s a mistake in the nested foreach loops. The following:
foreach($myMenu as $key => $val){
foreach($val as $k => $v){
$url = $k;
$link = $v;
}
$output .= “<a href=\”$url\” title=\”$key\” id=\”$key\”>$link</a><br />\n”;
}
echo $output;
The above doesn’t generate the actual URL in the href attribute (which is wrong in your output example as well). Instead, it inserts the second array key:
<a href=”text” title=”home” id=”home”>Home Page</a><br />
This is because the second foreach loop is overwriting variables, first storing $url=”url” and $link=”home.html”, then storing $url=”text” and $link=”Home Page”.
This can be corrected by using the key to create variable variables that contain the value from the array.
The nested loops below will generate the desired output.
foreach($myMenu as $key => $val){
foreach($val as $k => $v){
$$k = $v;
}
$output .= “<a href=\”$url\” title=\”$key\” id=\”$key\”>$text</a><br />\n”;
}
echo $output;
Everything else looks solid. Great read!
(NOTE: I’m crossing my fingers and hoping that HTML tags work in comments, because I used a bunch of them. My apologies if this comment comes out all jacked up.)
Jason Lengstorf: Thanks for catching that error and pointing out the solution. I thought I had tested all the code but that one made it by and also made it through the proofing. Ooops
honestly, if you think that
“An array is not an easy concept to grasp at first since an array has many values, or elements, and can be used in so many ways.”
aka. arrays are HARD, you should not freakin be in software development – if it doesnt come naturally you will always suck compared to those that it does for.
Hi there.
2 things first
1) Your bloging software looks hungry – you’ve got some $ missing in:
foreach (array as $value) (…)
2) While it’s true that you can declare arrays by simply calling $newArray[] = ‘some value’; witch will give you a nice 1 element array, it’s syntax-wise correct to declare the variable as array by doing:
$newArray = array();
$newArray[] = ‘some value’;
Else you’ll get an error at E_ALL error reporting level.
Aside from those two things – great explanation for the beginners among us
Fredrik –
For those of us who will never be as smart as a “fredrik,” tutorials and explanations like this are very helpful and appreciated.
Very interesting and useful information. I’m not so good in programming so I will give a link to our developer to explain me some details.
December 28th, 2009 at 3:25 pm
I just found this page via a net.tutsplus.com post. It’s nice roundup of info on PHP arrays.
I did notice that in the “Accessing Indexed Array Values” section you say that “value-2″ corresponds to index key 3 when it should say it corresponds to index key 1.
You might want to fix that, zero indexing trips people up enough when they’re getting started.
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!