Learn PHP Second Step

Learn PHP Second Step

This tutorial will continue to guide you through getting started with PHP arrays and loops.


Beginners: In order to fully understand these concepts, it is highly recommend that you first read Part 1. Part two of this series will walk through using core PHP principles that assist in everyday coding. This includes creating and using arrays and loops to store and retrieve data when you please.


An array stores multiple values in one single variable.An array is what you turn to when you find yourself creating similar variables over and over. Two words are used when referring to the contents of an array. Those words are “key” and “value”. Every array has at least 1 key and value. They will always come in pairs as the key refers to the value.

There are three types of arrays:

Multidimensional arrays are simply arrays within arrays. Let’s take a brief look at the first two.

Associative Arrays

An associative array is helpful in that the key is declared by the programmer somewhere thus giving context to the value. For example I will create an array containing personal information about myself. Below you will see two ways of laying out the array in PHP. The purpose of the second is only for organization and ease of reading. As Jeffrey mentioned in part one of this series, PHP is not white-space sensitive.

<br /><?php $personalInfo = array(<br />"name"=-->"Anandvenugopal",<br />"occupation"=>"Web Developer",<br />"location"=>"Calicut,Kerala");<br />?><br />
<br /><?php $personalInfo = array(<br />'name'=-->'Anandvenugopal',<br />'occupation'=>'Web Developer',<br />'age'=>24,<br />'location'=>'Calicut,Kerala');<br />?><br />

That’s great and all – but how do I get my information to display in HTML? I’m glad you asked! It’s very similar to displaying a variable but you add one little extra piece of data: the key.

<br />My name is <?=$personalInfo['name']?><br />and I am a <?=$personalInfo['occupation']?><br />in <?=$personalInfo['location']?><br />and am <?=$personalInfo['age']?> years old.<br />

Wait a second? What’s this is shorthand PHP for . In part one you learned that the echo command is similar to print in other languages. The shorthand PHP is just one way to write less code while working.

Numeric Arrays

Sometimes you don’t need to have a word associated with a value within an array. In that case you will use a numeric array which is actually created by default in PHP. Above we used the equal sign followed by the greater than sign (=>) to set array values to keys. With numeric arrays you can simply set the values and the key is assumed incrementally. Let’s take a look:

<?php<br />$personalInfo = array(<br />'name'=>'Anandvenugopal',<br />'occupation'=>'Web Developer',<br />'age'=>24,<br />'location'=>'calicut,Kerala');<br /><br />$fruit = array('apple','orange','grapes');<br />?><br />

As you can see we have done nothing but put values in this array. PHP took care of the keys for us. As far as you beginners are concerned keys ALWAYS start at the number 0 and increase by 1 with each new array element. As you go deeper into learning about arrays you will learn that you can manipulate them at will – but that is not covered here today. “How do I know what key to use”, you may ask. The easy way in our example is just to start at zero and find your element. For example the key for “apple” is 0, the key for “orange” is 1 and the key for “grapes” is 2. Pretty simple, huh. Well sometimes your arrays will get huge and go up into the 10s and possibly hundreds. No one wants to sit there and count that mess. Your first instinct may be to simply run “echo $fruit” but it will only spit out the word “Array”. PHP gives us a few simple ways to review our array data. Let’s look at two of them.

<br /><?php<br />$personalInfo = array(<br />'name'=>'Anandvenugopal',<br />'occupation'=>'Web Developer',<br />'age'=> 24,<br />'location'=> Calicut,Kerala');<br />$fruit = array('apple','orange','grapes');<br />print_r($personalInfo);<br />var_dump($fruit);<br />?><br />

Note that running these in your browser may produce something quite nasty looking. The first array will especially be unattractive and perhaps difficult to read. It may benefit you to throw <pre></pre> tags around those two commands so that the white space is pre-formatted correctly. Assuming you have placed these tags around the command you should have the following printed back to you:

Array(<br />[0] => apple<br />[1] => orange<br />[2] => grapes)<br />array(4) {["name"]=>string(11) "Anandvenugopal"<br />["occupation"]=>string(13) "Web Developer"<br />["age"]=>int(24)<br />["location"]=>string(16) "Calicut,Kerala"}

The first function, print_r(), will simply print the structure and contents of your array. The <strong>keys</strong> will be on the left in brackets and the <strong>values</strong> will be to the right of the corresponding keys. In the second function, <em>var_dump()</em>, you learn and bit more about your data. Notice the “age” key in the $personalInfo array. The value is not in quotes like the other values are. I did this so that you could distinguish between two types of data in PHP. Anything in quotes is considered a <strong>string</strong> and in the case of the “age” data it is an <strong>integer</strong>. I won’t go into details of the other types of data but I point this out because the <em>var_dump()</em> function gives you some useful information.

Notice the first bit which comes in the first line “<em>array(<strong>4</strong>)</em>”. The first bit dumped saying “This is an array and it contains 4 sets of data”. Going down to the next line you get your key you see the first key and then it says “<em>string(<strong>11</strong>)</em>”. This is saying “This is a string and it is 11 characters in length” (keep in mind that a blank space is considered a character). Jump down to the “age” key and notice it says <em>int(<strong>23</strong>)</em>. This is saying “This is an integer with a value of 23?.

Now that you know how to use <em>print_r()</em> and <em>var_dump()</em> we will move on to looping through this data.

<h4>Multidimensional Arrays</h4>

As mentioned above a multidimensional array is simply an array that contains at least one additional array as a value. I will run with the “personalInfo” example and create an array for a staff team.

<br /><?php $company = array(<br />'info'=>array(<br />'name'=>'Zravastechnologies',<br />'location'=>'Calicut,Kerala',<br />'website'=> 'http://zravastech.com'),<br />'staff'=> array(<br />array('name'=>'Shanbal','position' => 'Marketing Manager'),<br />array('name'=>'Premjith','position'=> 'Cheif Software Architect'),<br />array('name'=>'Anandvenugopal','position' => 'Cheif Innovation Officer'),<br />array('name'=>'Shivin','position' => 'Cheif Operations Officer')));<br />?><br />

As you can see multidimensional arrays can get intricate. This is an odd example because typically this type of data would be stored in a database and pulled in with PHP later. However, for the sake of learning about arrays we will start with the data within PHP. The first key in this array is called ‘info’ and it’s value is actually an associative array containing company information. The second key of our $company array is ‘staff’ and it’s value is a numeric array. Let’s take a look at the structure before we begin. Running print_r($company) will produce the following:

<br />Array ( [info] => Array (<br />[name] => Zravastechnologies<br />[location] =>Calicut,Kerala<br />[website] => http://zravastech.com)<br />[staff] => Array ( [0] => Array (<br />[name] => Shanbal<br />[position] =>Marketing Manager )<br />[1] =>Array (<br />[name] => Premjith<br />[position] => Cheif Software Architect )<br />[2] => Array (<br />[name] =>Anandvenugopal<br />[position] => Cheif Innovation Officer )<br />[3] => Array (<br />[name] => Shivin<br />[position] =>Cheif Operations Officer )))<br />

Now our company information is ready to be accessed. We access the internal arrays the same way we accessed our personal information earlier. Here’s an example of using data from this multidimensional array:

<h1><?=$company['info']['name']?></h1><br /><br />Located in <?=$company['info']['location']?><br />and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a><br /><br /><h2>Our Marketing Manager</h2><br /><p><?=$company['staff'][0]['name']?></p>

Now that we have a grasp on arrays lets jump into loops which will minimize the time we spend parsing the array data.


Loops will come in quite handy as the amount of data you work with increases. We’ve gone into arrays so that naturally leads us to loops. In the last code snippet we listed a staff member within the <em>$company</em> array. What if we want to cycle, or loop, through each staff member and display the information in a uniform fashion? Well in comes the <em>foreach</em> loop. Just like the function sounds it will do a specific action <em>for each</em> of the elements within an array or object. It typically looks like this:

<br /><?php<br />foreach($array as $key => $value) {<br />...some code here<br />}<br />?><br />

Notice the three variables passed to this function. The first is simply the array we are working with. The second and third variables are defined by YOU and can say anything you want. These are what refer to the array’s data inside the curly brackets. We will look at this in a moment. But first, just like the <em>echo</em> command has a shorthand or alternate syntax, <em>foreach</em> has something that will help transverse between PHP and HTML. This way it keeps the code as clean as possible. It looks like this:

<br /><? foreach($array as $key => $value) : ?><br /><p>Some html and some php will go here</p><br /><? endforeach; ?><br />

You will see this format in <em>if</em> statements and <em>while</em> loops as well (in WordPress for example). Now that we’ve looked at the format of this function let’s put it in action. Going back to the company information array let’s build a nice page with that data

<br /><?php<br />$company = array(<br />'info' => array(<br />'name' => 'Zravastechnologies',<br />'location' => 'Calicut,Kerala',<br />'website' => 'http://zravastech.com'),<br />'staff' => array(<br />array('name'=>'Shanbal','position' => 'Marketing Manager'),<br />array('name'=>'Premjith','position'=> 'Cheif Software Architect'),<br />array('name'=>'Anandvenugopal','position' => 'Cheif Innovation Officer'),<br />array('name'=>'Shivin','position' => 'Cheif Operations Officer'))<br />);<br />?><br /><h1><?=$company['info']['name']?></h1><br /><p>Located in <?=$company['info']['location']?><br />and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p><br /><h2>Our Staff</h2><br /><ul><br /><?php foreach ($company['staff'] as $person) : ?><br /><li><?=$person['name']?> is our <?=$person['position']?></li><br /><?php endforeach; ?><br /></ul><br />

In this instance the foreach loop cycles through each staff member and displays the HTML and PHP we told it do. I knows exactly how many staff members are in the array so it stops once it gets to the end. I’m sure you can see how useful this can become.

<h3>Additional Resources</h3>
Although this tutorial may seem to ‘unleash the power of arrays and loops’ it really just scratches the surface. I highly encourage anyone interested (and that means YOU if you’re still reading this) to read through the PHP online docs for the version you are using. You can find them at <a title=”PHP: Hypertext Preprocessor” href=”http://www.php.net/”>php.net</a>. We only used one type of loop in this tutorial, the <em>foreach</em> loop. There are others like <em>for</em>, <em>do…while</em> and <em>while</em> that you will also gain use from knowing about.

You will see this format in <em>if</em> statements and <em>while</em> loops as well (in WordPress for example). Now that we’ve looked at the format of this function let’s put it in action. Going back to the company information array let’s build a nice page with that data

<br /><?php<br />$company = array(<br />'info'=> array('name'=>'Zravastechnologies',<br />'location'=>'Calicut,Kerala','website'=>'http://zravastech.com'),<br />'staff'=>array(array('name'=>'Shanbal','position' =>'Marketing Manager'),<br />array('name'=>'Premjith','position'=>'Cheif Software Architect'),<br />array('name'=>'Anandvenugopal','position'=>'Cheif Innovation Officer'),<br />array('name'=>'Shivin','position'=>'Cheif Operations Officer')));?><br /><?=$company['info']['name']?><br />Located in<?=$company['info']['location']?><br />and online at <a href="<?=$company['info']['website']?>"><br /><?=$company['info']['website']?></a>.<br />Our Staff<ul><br /><?php foreach ($company['staff'] as $person) : ?><br /><li><?=$person['name']?> is our <?=$person['position']?>;</li><br /><?php endforeach; ?></ul><br />

In this instance the <em>foreach</em> loop cycles through each staff member and displays the HTML and PHP we told it do. I knows exactly how many staff members are in the array so it stops once it gets to the end. I’m sure you can see how useful this can become.


  1. says

    Thank you for such a wonderful blog. Where else could one get this kind of details written in this kind of an incite full way? I have a presentation that I am just now working on, and I were trying to find such information.

  2. says

    I enjoy this fill someone in on, i didnrrrt appreciate a kismet of what you posted in here. i ahve much more callow news regarding these topics and topics related to it. some people may upon it immutable to understadn the english dialect but i notice it very calm following the privacy that has discover to generally be what’s todays policy.

  3. says

    Hey there! Someone in my Myspace group shared this site with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Fantastic blog and great style and design.

  4. says

    Good day there, I found out your internet site by the use of Google even as hunting for a relevant subject, your web website arrived up, it would seem very good. I’ve bookmarked it in my google bookmarks.

  5. says

    I feel this is one of the most significant info for me. And i am happy reading your article. But should commentary on some general issues, The website taste is great, the articles is really excellent :D. Just right activity, cheers.