ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Server Side Web Tutorial #5 - Working with PHP Indexed, Associative, and Multidimensional Arrays

Updated on May 6, 2014

Recap of Our Last Tutorial & This Tutorial's Goals

In our last tutorial, A Server Side Web Tutorial Series # 4 - PHP Conditional Statements we introduced all of the operators in the PHP language suite. One of the operators the union operator works exclusively on arrays. Other comparison operators work with arrays in a similar fashion as they do with other variables (e.g. equality, inequality). As far as conditional statements, again, there is one, the foreach looping statement is used exclusively with arrays. We presented an example of the foreach loop appealing to the readers intuitive reason knowing that in this tutorial we would be presenting a more rigorous treatment of array.

In this array we will indicate what arrays are, how to create them, go through a more formal presentation of the foreach statement, and demonstrate a number of PHP built-in functions which manipulate arrays.

What is an array? Why are arrays useful?

An array is a special variable which may has more than one value related to it. Consider the following example . Suppose our program had to store data about vegetables. One coul start out with:

$veg1 = "carrots";

$veg2 = "spinach";

$veg3 = "lima beans";

Now, let's suppose that you were developing a computer program which need to get the dollar value of all of the vergetables you had in stock. You would have to address each vegetable by a specific name $veg1,, veg2,....,etc. and then somehow manipulate another list with the vegetable price, $vegcost1, vegcost2,.....etc and then have a third set of variables which were related to amount of that vegetable that you had in stock. So, to compute your inventory at.cost you would have 3 unique variables for each vegetable times the number of vegetables.The coding of such an example could run into several hundreds if not thousands of lines.

Arrays were developed for just this type of problems.Arrays can hold many values under one name. In our situation we could have only three varible names for our example regardless of the number of vegetables we needed to keep track of: $vegetableName, $vegetableCost, and $vegetableAmount. Better yet, when we discuss multidimensional arrays we could refer to all of this information with one variable, $vegetable, in three dimensions.


Creating an Array

In PHP, the keyword array is used to create an array. There are three types of arrays in PH (from simplest to most complex):

  • Indexed arrays - Arrays with numeric index
  • Associative arrays - Arrays with named keys
  • Multidimensional arrays - Arrays containing one or more arrays

Ways to Create an Indexed Arrays

There are two ways to create arrays. For our vegetable example:

$vegetable = array("beans", "beets", "corn", "squash",);

that is select a variable name performing an assignment using the keyword array, and in parenthesis for string have the various items in quotes separated by commas. For numeric arrays it would just be the numeric values separated by commas.

The second way to create an array, choose the name for the variable and assign each variable value an index number enclosed in square brackets and assign a value to it. In this case each value is assigned in a spearate statement, and the index numbers must be unique.

Our array assignment would look like:

$vegetable[0] = "beans";

$vegetable[1] = "beets";

$vegetable[2} = "corn";

......etc.

Note: The index numbers as in most if not all programming languages begins with 0 and NOT 1.


Creating an Indexed Array

In this example we created an numeric indexed array with three values. The combination of the  index, (generally referred to as a key) is called a key/value pair
In this example we created an numeric indexed array with three values. The combination of the index, (generally referred to as a key) is called a key/value pair

Getting the Length of An Array: The count() Function

If we want to loop through our arrays and either print the arrays or perform some calculation, having the length of the array will give us the number of times we have to iterate through values.

The PHP count() function does exactly that. The format of the count function is quite simple:

count(the variable name of the array).

Looping Through an Indexed Array

Looping through a single index array is quite simple. In this example we use the count() function to determine the length of the array an process the array via the for loop.
Looping through a single index array is quite simple. In this example we use the count() function to determine the length of the array an process the array via the for loop.

Creating an Associative Array

An associative array the keys have names rather than numbers. What we would have for our example of vegetables if we wanted to create an arry of the cost of each vegetable would be the following.

$ vegetable_cost= array("beets"=> 0.92, "corn" =>0.40, "celery" => 0.63);

or similar to the indexed array, substituting the vegetable name as the key rather than a number:

$vegetable_cost["beets"] = 0.92;

$vegetable_cost["corn"] = 0.40;

$vegetable_cost["celery"] = 0.63;

Creating & Looping Through an Associative Array

In this example, we created the associative array. Note, because the keys are strings rather than integers we use the foreach construct to loop through the array.
In this example, we created the associative array. Note, because the keys are strings rather than integers we use the foreach construct to loop through the array.

Creating a Multidimensional Array

In our original example with vegetables, we created three variable and hence three arrays : one to keep the name of the vegetable, one to record the cost, and a third to keep the stock amount. Although this is an improvement of a variable name for each vegetable, cost, and amount we have a better way of representing this. We can create a multidimensional array.

Thinking in terms of what we would like to store is the vegetable name, cost, and amount we can use a two-dimensional array as follows:

$vegetables = array (

array("beans", 0.40, 18),

array('beets",0.99,8),

array("corn", 0.54, 26),

array celery, 0.65, 100)

);

Essentially, we have created an array $vegetables, which contains four arrays. One does not have to stop at two dimensions. PHP does not have any restriction on the nesting of the arrays, so there could be three, four, five or more arrays. However managing that becomes quite complex. There becomes a better solution for this, using data bases. Which will be covered in future tutorials.

We now turn out attention as to how to manipulate arrays.


Looping Through a multidimensional Array

In this example, we demonstrate looping through a two dimensional array. Note that the index value for the first entry starts at 0 NOT 1. This is a very common mistake when beginning to learn about arrays.
In this example, we demonstrate looping through a two dimensional array. Note that the index value for the first entry starts at 0 NOT 1. This is a very common mistake when beginning to learn about arrays.

Were The Examples in This Tutorial Clear?

Cast your vote for Please rate and/or comment on this tutorial

Wrap Up and What's Next

In this tutorial we looked at the three types of arrays supported in PHP: the indexed, associative, and multi-dimensional array.

The indexed array is quite simple. Integers starting at 0 are used with the variable name to choose the elements to process.

An associative array uses names as the index. Because we are indexing by a name rather than a number we use the foreach statement for the looping construct.

The multi-dimensional array is bet though of as a nesting process, "an array within an array". There is no limit to the number of dimensions of the array however working with more than three dimensions becomes combersome and error prone. There are bettes solutions.

The are a large number of built-in PHP functions to process arrays. Our next tutorial will focus on some of them starting with sorting.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)