Many things that make the world as we know it possible are so commonplace that we forget they even exist. One of my favorite examples is the elevator; the idea of a lifting platform or box is very old but it had to wait for the Industrial Revolution to become a practical device. When Mr. Otis installed his first successful elevator in the brand-new E. V. Haughwout Building in 1857, he opened the path for the vertical growth of metropolises like New York City and São Paulo.

Another favorite invention of mine are tables. Not of the dining sort, though they too are immensely important both for eating and working, rather the type that stores information. Such tables are part of our daily life in hundreds of different variations. In many countries, milk, butter and cereal containers display a table of nutritional values – though I wonder who reads and understands them. Most papers, for those that still read them in print, are organized as a sort of table. Many cities, especially in the New World (herein extended to include Australia and New Zealand), are organized as a table with streets as rows and avenues as columns. Children start out with tables as soon as they begin to learn multiplication and divisions; in fact, Portuguese has an interesting word for multiplication tables: taboada, roughly, “a thing put on a table!” Engineering is unthinkable without tables, and tables are the backbones of management techniques like Operational Research and Game Theory.

## What are Arrays?

Tables organize data in such a way that we can easily find correlations or perform straightforward computations. An array is essentially a way to organize data in a table-like manner. The name “array” comes from the same Latin roots as the word “arrangement.”

To help us understand arrays better, let’s begin with a table called Prices NYC to show the price of a hamburger in New York City is one dollar:

We can write it as an array called, you’d never guess, `pricesNYC`:

`pricesNYC ("hamburger"=1)`

That piece of information is so simple that representing it on a table or an array seems a waste of time. But what if we add the price of a side of fries? We could write:

and:

`pricesNYC ("hamburger"=1, "fries"=.70)`

This is an associative array. In an associative array, each and every value is identified by a label, or sequence of labels, called a key. hamburger and fries are the keys in this example, and their values are 1 and .70 respectively. Keys can also be a numerical sequence instead of labels. In such cases the array is said to be non-associative. Our example as a non-associative array would be:

`pricesNYC (0=1, 1=.70)`

The value at index (or key) 0 is 1 and the value at index 1 is .70. (In most programming languages, non-associative arrays start with an index of 0 for largely historical and mathematically convenient reasons.)

Sometimes the indexes are not explicitly given but the values are still accessible by their position.

`pricesNYC (1, .70)`

Sticking with the associative array, we could create a second table and array if we want to show the same prices for Los Angeles:

`pricesLA ("hamburger"=1.30, "fries"=.50)`

Alternatively, we could combine the data from the two tables together like this:

```prices ("New York"=pricesNYC ("hamburger"=1, "fries"=.70),
"Los Angeles"=pricesLA ("hamburger"=1.30, "fries"=.50))```

We’ve begin to create arrays within arrays and each value is now identified by the sequence of labels. For example, the key for the price of a burger in NYC is now New York, hamburger. In `prices`, the top-level array has two keys, New York and Los Angeles. Each of these keys point to values that are actually other arrays. These second-level arrays have the labels hamburger and fries which finally point to a number which is the desired price.

In a non-associative fashion, the array would look something like this:

```prices (0=pricesNYC (0=1, 1=.70),
1=pricesLA (0=1.30, 1=.50))```

The price of a burger in NYC is found here with the index 0 0.

## Creating Arrays

Now that the concept of arrays is established, let’s move on to discussing how PHP implements them and, more importantly, how we can create them. The most orthodox method of creating an array is to use the `array()` construct:

``````<?php
\$pricesNYC = array();``````

Our array as created is empty. We can then assign values to the array using the key specified in brackets:

``````<?php
\$pricesNYC["hamburger"] = 1;
\$pricesNYC["fried"] = .70;``````

Alternatively we could have populated the array at the same time we create it using the syntax key `=>` value. The key/value pairs are separated by comma:

``````<?php
\$pricesNYC = array("hamburger" => 1, "fries" => .70);``````

When I was first learning PHP, I often had to go back to the documentation to check whether the correct operator was `=>` or `->`. One day I came up with the mnemonic “this key will be equal to that value” and now I easily remember `=>` is the correct choice.

So what do the above examples look like for non-associative arrays?

``````<?php
\$pricesNYC = array();
\$pricesNYC[0] = 1;
\$pricesNYC[1] = .70;``````

and:

``````<?php
\$pricesNYC = array(0 => 1, 1 => .70);``````

If all you want is a non-associative array, it isn’t necessary to specify the index. PHP automatically uses the next integer value in the key sequence, starting at 0, for key if you do not provide one. These examples produce identical non-associative arrays to those we just saw:

``````<?php
\$pricesNYC = array();
\$pricesNYC[] = 1;
\$pricesNYC[] = .70;``````

and:

``````<?php
\$pricesNYC = array(1, .70);``````

PHP arrays can have mixed keys, that is, some keys can be strings and other can be indexes. So far we’ve seen keys that were either strings (like hamburger) and integers (0).

Now let’s make things a little more interesting by transforming the two-city table into an array. The creation of the empty array is, as before, straightforward:

``````<?php
\$prices = array();``````

Also straightforward is how the array can be populated with the brackets syntax:

``````<?php
\$prices["New York"]["hamburger"] = 1;
\$prices["New York"]["fries"] = 0.70;
\$prices["Los Angeles"]["hamburger"] = 1.30;
\$prices["Los Angeles"]["fries"] = 0.50;``````

or, for non-associative arrays:

``````<?php
\$prices[1][0]=1;
\$prices[1][1]=0.7;
\$prices[0][0]=1.3;
\$prices[0][1]=0.5;``````

What about assigning all the values when we create the array?
Since our table has two levels, the first being the city and the second one the item, we declare the array like a series of arrays within another:

``````<?php
\$prices = array("Los Angeles" => array("hamburger" => 1.3, "fries" => 0.5),
"New York" => array("hamburger" => 1, "fries" => 0.7));``````

You’ll find you often represent the keys with variables when you work with arrays. This is very useful for creating arrays whose values can be mechanically computed. For example, this loop creates an 10-element array with values that are the square of the keys:

``````<?php
\$squares = array();
for (\$key = 0; \$key < 10; \$key++) {
\$squares[\$key] = \$key * \$key;
}``````

The resulting array `\$squares` is populated the same as if we had written:

``````<?php
\$squares = array();
\$squares[0] = 0;
\$squares[1] = 1;
\$squares[2] = 4;
\$squares[3] = 9;
...
\$squares[9] = 81;``````

## Using Arrays

We’ve learned how to create and fill arrays with values, so how about retrieving these values? To use a value in an array you only have to refer to it with the name of the array variable and the desired index. This way, the price of a hamburger in New York is:

``````<?php
\$price = \$pricesNYC["hamburger"];``````

or:

``````<?php
\$price = \$prices["New York"]["hamburger"];``````

If we want the cost of a snack (burger+fries) in Los Angeles, we could calculate it as:

``````<?php
\$price = \$prices["Los Angeles"]["hamburger"] + \$prices["Los Angeles"]["fries"];``````

Suppose we want a list of the cost of snack is all towns. As good programmers we wouldn’t dream of repeating the statement for all cities. Rather, we’d try to write a loop instead. It’s a good idea, but which looping construct should we use? Let’s try a `for`-loop:

``````<?php
for (\$key = _start_; \$key <= _end_; \$key++) {
\$price = \$prices[\$key]["hamburger"] + \$prices[\$key]["fries"];
}``````

Hrm… that doesn’t work because the keys to the array are strings! We don’t know what to use for `_start_` or `_end_`. Fortunately, PHP has a `foreach`-loop that runs through every element of an array, which is exactly what we want to do:

``````<?php
foreach (\$prices as \$snack) {
\$price = \$snack["hamburger"] + \$snack["fries"];
}``````

This loop will run through array `\$prices` two times as it has two first-level elements. On the first run, it will extract the array that has the prices for burgers and fries in New York. We call this array \$snack. The prices are then added by looking up the values using the keys hamburger and fries. Of course in a real script something else should happen to `\$price`, like being printed or sent to a data table, but we don’t need to do that here. The first-level array is then automatically incremented to the next element and the loop makes the second-level array with prices for Los Angeles available as \$snack.

It is possible to nest `foreach`-loops. Just for the sake of one last example, let’s compute the prices using two loops. If this is confusing, copy it down with pen and paper (a centuries old study device that does wonders for enlightenment) and carefully read through it.

``````<?php
foreach (\$prices as \$city => \$snack) {
echo  "<b>" . \$city . "</b><br>";
foreach (\$snack as \$item => \$price) {
echo \$item . " = " . \$price . "<br>";
}
}``````

`foreach` can use the `=>` syntax to make the both the current key and value available to the body of the loop. The output of this loop will send the prices of hamburgers and fries grouped by city to the browser.

## Conclusion

Arrays are a very, very important and versatile data structure. They are handy for grouping all sorts of related information together, and are really easy to use once you get the hang of them. But you can do much more with them than just adding prices. I am fond of using them for customizing scripts, creating key/value pairs for data like website domain name, description, keywords, database login credentials, etc. Also note the PHP super global variables like `\$_GET`, `\$_POST`, `\$_SESSION` and `\$_SERVER` are all arrays. Now that you’re on your way to becoming a proficient array user, you’ll notice them all around you!

Gee, all those tables and arrays made me hungry. I think I’m going to take the elevator down and have a burger with fries. Or rather do I fancy fish and chips?

Image via keko64 / Shutterstock

Tags: Beginner

• http://www.get2know.me Anthony Wlodarski

Basic article. Seems like a clear explanation on the use of arrays for a beginner. Have you ever thought on the complexity of variable assignment using bracket syntax on uninitialized arrays? E.g. “\$a[] = ‘foo';” versus “\$a = array(); \$a[] = ‘foo';”.

• http://phpmaster.com J Armando Jeronymo

Hi Anthony,
thanks for your comments and kind words. Personally, I try never to leave a variable uninitiated for the sake of security and also because I feel it makes the code easier to read. But you’re right in that I should give some examples in future articles.
Take care,
A J

• http://gumz-ex-press.com/ Gumz

Very detailed article on ways to use array in php. Beginners should look into this.

• J Armando Jeronymo

Hi Gumz,
thanks for the kind words. I hope to be useful to someone! By the way, I’ve visited yr blog and bookmarked yr article on PHP objects for reading ASAP. Hope it cures me of my OOP fears! :-)
Take care
A J
Take care

• http://cochesaurus.com Roberto Navas

Very good article and is very easy to understand. I also like the cool example of hamburgers and meals.

• J Armando Jeronymo

Hi Roberto,
thanks for your encouraging words but please bear on mind that most of what makes an article interesting and readable is the editor’s, not the author’s work. Kudos to them!
BTW, I loved yr medal tutorial. Pls write more!
Take care
A J

• Edene

I’m a beginner….and thank goodness articles like this one are being written!

• J Armando Jeronymo

Hi Edene,
Thank YOU! Being able to be of help is one of the greatest satisfactions I draw in life. I hope you soon become a master in PHP.
Take care
A J

• http://www.vforteachers.com Valerie Coskrey

Ditto! Many thanks for the gentle learning curve built into the article. I need just that as I learn php. This article really helped me understand.

• http://jeffshamley.com Jeff Shamley

great article for PHP beginners. thanks for writing!

• J Armando Jeronymo

Hi Jeff,
thanks for commenting! and thanks for teaching us where to go in Chicago for a beer! I enjoyed yr writing too!
Take care,
A J

• Gorky

Hi Armando!
Thanks for this great article with nice examples.One question: How do I programmaticaly expand the (array prices in PHP?
?php
\$prices = array(“Los Angeles” => array(“hamburger” => 1.3, “fries” => 0.5),
“New York” => array(“hamburger” => 1, “fries” => 0.7));

eg. a user post a new city(Paris, with say 2\$ for a hamburger and \$1.5 for fries)
thanks
Gorky

• J Armando Jeronymo

Hi Gorky!
Thanks for yr kind words! Regarding yr question, I’ll assume you know how to read user posted data and those data are simply the name of the city and the prices of hamburger and fries in my beloved Paris. Calling them respectively \$name_of_town, \$price_hamburger and \$price_fries, all you have to do is this:
\$prices[\$name_of_town] = array (“hamburger” => \$price_hamburger, “fries” => \$price_fries);
This will add (push) the new item to (into) the end of the array.
Hope the above helps!
Take care!
A J

• Gorky

Thank you very much for your friendly help!

• www.php4m.net Rakesh Gautam

Hi Armando
thats a very useful artical for beginers
:)

• http://Www.novate.co.uk Mark Snape

Good beginners article armando, but there might be a mistake?
after you talk about non-associative arrays not requiring an index, you then show two examples specifying the index, one of which is a repeat of earlier (indexed) code.
I think you wanted something like
\$pricesNYC = ARRAY(1,.70);
?

• J Armando Jeronymo

Hi Mark,
you’re absolutely right! The arrays you mention should be
<?php
\$pricesNYC = array();
\$pricesNYC[] = 1;
\$pricesNYC[] = .70;

and, as you suggested,

\$pricesNYC = array(1,.70);

I think I must have done a copy/paste and got my attention distracted before editing the results. I visited yr website and saw you're in Mansfield. I know a bit of your part of the world. My wife spent six months in Sheffield before we married and I visited her these two or three times.
Thanks for pointing out my mistake. Take care.
A J

• http://zaemis.blogspot.com Timothy Boronczyk

Thanks for the heads up, Mark. I’ve merged Armando’s corrections into the article, so it should be correct now.

• http://www.rebornmedia.co.uk Ally

Really good article. Could have done with reading it a few years ago!

• http://www.codeandwebdesigns.com Earl Gile

Great tutorial thanks, I am working on a project where I can not get an array to work I am sure I will find the answer here.

• Chris Ward

Great article and clear style of writing. I have added the feed and look forward to future articles.

• Franko

Great article. I like you connect array concept with real life; hamburger, fries and tables :). I think that is much easier for everybody to get into the problem. After reading this, you know what? I’m hungry too. I need a fridge :)

• Jonas Okwara

• http://www.riak.uk.com Web Design Crawley

Great Article! I really struggled to get my head around arrays before reading this. Now its easy :-)

• John

Thank you; very helpful article for me, a beginner. I worked through the nested foreach loop example and found that the second “{” on line 5 throws an error. Deleting it solved the error. Also, am curious about the need for “\$totalItemPrice = 0″ on line 4, since it seems not to be used. Again, thank you. It was very helpful to work through your examples.

• J Armando Jeronymo

Hi John!
Indeed the { will throw an error because I’ve forgotten to add the closing one. And because its contents is a one line instruction, it was not missed when you removed it as { and } are used to enclose blocks of conditional (IF) or repetitive (WHILE, FOR, FOREACH) instructions.
As form the \$totalItemPrice = 0, it does not interfere with the logic of the program as PHP self initializes all variables it uses. However, it is considered, by some at least, a good programming practice to explicitly initialize all variables. One reason for that is readability: you can tell where that quantity comes into the context. The other is security, even if someone tries to define the variable outside the script (as is possible to do under certain circumstances by requesting something like http://theexamplesite.com?totalItemPrice=1000 from a browser) the script will reset the value before the relevant part executes.
Hope you find the above clear and useful.

• http://zaemis.blogspot.com Timothy Boronczyk

Sorry about that, guys. I’ve fixed the final example.

• Rey

Hi Armando,
thanks for the heads up on arrays.
Btw, I’m a visual learner so can you recommend a great PHP video tutorial from beginner to advance?
cheers and keep up the good work!

• http://fhprojects.org Fabricio H

Very nice article, I was doing the exercise while reading and making meaningful comments. I’m also a beginner… I could say I’m finally grasping it.
Thanks!

• Gildus

What about the ArrayList or the STD class?, is valid too ?
Thanks!

Sir, thank you for your good example. It always helps me to understand how it work. Congratulation sir;

• http://www.scriptvenue.com Arvind

Hi
Nice article, explained in a simple way.
Thanks…

### Recommended for you

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.