Picking up where part 1 of this series left off, this tutorial will continue to guide you through getting started with PHP arrays and loops. Basic fundamentals will be taught alongside their equal partners used in popular software such as Wordpress.
Overview
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.
Array of Light
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: Associative, Numeric, and Multidimensional. 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.
<?php
$personalInfo = array("name"=>"Erik Reagan","occupation"=>"Web Developer","location"=>"Savannah, GA USA");
?>
<?php $personalInfo = array( 'name' => 'Erik Reagan', 'occupation' => 'Web Developer', 'age' => 23, 'location' => 'Savannah, GA USA' ); ?>
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.
<p>My name is <?=$personalInfo['name']?> and I am a <?=$personalInfo['occupation']?> in <?=$personalInfo['location']?> and am <?=$personalInfo['age']?> years old.</p>
Wait a second? What's this <?=...?> mess all of a sudden? Well using <?=?> is shorthand PHP for <?php echo ... ?>. 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
$personalInfo = array(
'name' => 'Erik Reagan',
'occupation' => 'Web Developer',
'age' => 23,
'location' => 'Savannah, GA USA'
);
$fruit = array('apple','orange','grapes');
?>
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.
<?php
$personalInfo = array(
'name' => 'Erik Reagan',
'occupation' => 'Web Developer',
'age' => 23,
'location' => 'Savannah, GA USA'
);
$fruit = array('apple','orange','grapes');
print_r($personalInfo);
var_dump($fruit);
?>
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
(
[0] => apple
[1] => orange
[2] => grapes
)
array(4) {
["name"]=>
string(11) "Erik Reagan"
["occupation"]=>
string(13) "Web Developer"
["age"]=>
int(23)
["location"]=>
string(16) "Savannah, GA USA"
}
The first function, print_r(), will simply print the structure and contents of your array. The keys will be on the left in brackets and the values will be to the right of the corresponding keys. In the second function, var_dump(), 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 string and in the case of the "age" data it is an integer. I won't go into details of the other types of data but I point this out because the var_dump() function gives you some useful information.
Notice the first bit which comes in the first line "array(4)". 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 "string(11)". 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 int(23). This is saying "This is an integer with a value of 23".
Now that you know how to use print_r() and var_dump() we will move on to looping through this data.
Multidimensional Arrays
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.
<?
$company = array(
'info' => array(
'name' => 'Awesome Web Company',
'location' => 'Savannah, GA',
'website' => 'http://weAreAwesome.com'),
'staff' => array(
array('name'=>'Kermit the Frog','position' => 'CEO'),
array('name'=>'Hiro Nakamura','position' => 'Art Director'),
array('name'=>'Willy Wonka','position' => 'Web Developer')
)
);
?>
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:
Array
(
[info] => Array
(
[name] => Awesome Web Company
[location] => Savannah, GA
[website] => http://weAreAwesome.com
)
[staff] => Array
(
[0] => Array
(
[name] => Kermit the Frog
[position] => CEO
)
[1] => Array
(
[name] => Hiro Nakamura
[position] => Art Director
)
[2] => Array
(
[name] => Willy Wonka
[position] => Web Developer
)
)
)
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> <p>Located in <?=$company['info']['location']?> and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p> <h2>Our CEO</h2> <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
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 $company 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 foreach loop. Just like the function sounds it will do a specific action for each of the elements within an array or object. It typically looks like this:
<?php
foreach($array as $key => $value) {
...some code here
}
?>
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 echo command has a shorthand or alternate syntax, foreach has something that will help transverse between PHP and HTML. This way it keeps the code as clean as possible. It looks like this:
<? foreach($array as $key => $value) : ?> <p>Some html and some php will go here</p> <? endforeach; ?>
You will see this format in if statements and while 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
<?
$company = array(
'info' => array(
'name' => 'Awesome Web Company',
'location' => 'Savannah, GA',
'website' => 'http://weAreAwesome.com'),
'staff' => array(
array('name'=>'Kermit the Frog','position' => 'CEO'),
array('name'=>'Hiro Nakamura','position' => 'Art Director'),
array('name'=>'Willy Wonka','position' => 'Web Developer')
)
);
?>
<h1><?=$company['info']['name']?></h1>
<p>Located in <?=$company['info']['location']?> and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p>
<h2>Our Staff</h2>
<ul>
<?php foreach ($company['staff'] as $person) : ?>
<li><?=$person['name']?> is our <?=$person['position']?></li>
<?php endforeach; ?>
</ul>
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.
Additional Resources
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 php.net. We only used one type of loop in this tutorial, the foreach loop. There are others like for, do...while and while that you will also gain use from knowing about.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.










User Comments
( ADD YOURS )jonatan September 11th
great for newbies
( )Jason September 11th
Great article for learning php but there are couple things that people may find confusing.
You have print_r assigned to the personalInfo array and var_dump assigned to the fruit array then the results show that the var_dump was used on personalInfo and the print_r was used on the fruit.
In the section on multidimensional arrays you use shorthand instead of which I always read was bad. Things may have changed, I could be smoking crack, or I’ve been tricked into typing 3 unneeded letters all this time.
( )Chris September 11th
Great, thanks so much for this! So simple to follow, you guys make it look easy.
I’ve never actually seen “endforeach;” in use, rather opening and closing brackets…
$value) { ?>
Some html and some php will go here
Can’t wait for the next one, hope it’s real soon!
( )SoN9ne September 11th
Short hand is not bad, its just recommended to not use it because most servers are not setup to use it. It is a good rule to always use <?php instead of <? when programming because then all servers can use your code no matter what the short tag setting is. Personally i never use the short tags. I write a few open source projects as well as develop a corporate social networking blogging platform that specializes in SEO. I would say this is a very nice tutorial, it is easy to read and understand. Nice job on this.
( )Momo September 11th
Be careful at this
<?= wrong for php5 version
use this :
<?php echo ‘…………………..’;
A bientôt
( )Evan September 11th
Nice tutorial. Like said before you use shorthand PHP tags in some places and full tags in other places.
( )Chris Robinson September 11th
Great tutorial
( )insic September 11th
at last its here. its quite a long wait. hehehe thank you very much.
( )insic2.0 September 11th
why my other username are block in nettuts. y i cant comment?
( )sinned September 11th
wow i am muted. why?
( )Make Design, Not War September 11th
Nice addition to the series… definitely for newbies, but I probably fall under that umbrella somewhere so I’m just happy to see more easy to follow tutorials out there like this. Looking forward to seeing the next pieces of this series! Thanks for the post
( )Erik Reagan September 11th
@Jason
( )I noticed the print_r and var_dump swap (along with a couple of other minor issues) this morning and just didn’t get my corrections to the editor in time. I promise to be a better proof reader next time
Josh September 11th
Thanks for this. I am really excited about this series
( )Dan September 11th
yeah, continued
( )Gonzalo September 11th
@Momo, I think it’s enabled by default, maybe your hosting has disabled it. You can enable it from php.ini or with a .htaccess file. Check the PHP documentation: http://www.php.net/manual/en/ini.core.php
( )Paul Gendek September 11th
I use short tags when it’s just a basic LAMP server, and the echo shorthand is best used in direct HTML code – easiest to type, and easiest to read later
( )Philo September 11th
Nice Article!
( )Shane September 11th
interesting post. Also interesting in reading some of these comments too.
@insic, @sinned – not quite sure what you’re both getting at. It seems you’re mentioning that you cannot comment, yet your comments are shown.
Hmmm…
( )Shane September 11th
Oh yeah – see what you mean – comment doesn’t appear immediately.
Is that why you keep submitting 2 consecutive comments insic?
( )Erik Reagan September 11th
Thanks for the kind remarks thus far.
I just realized my “Loops” header was edited. It was a mixture of a nerd & shakespeare joke. Originally it read “Wherefore Art thou Loops”
( )Miles Johnson September 11th
Decent basic article but DO NOT USE THE FOLLOWING:
The opening tag must be <?php not <?. The later is outdated and will not work on some windows servers and environments.
Stop using <?= also to echo your data, that is old and incorrect stated above. In PHP 5.3 that is soon to come out, those tags will no longer be valid and will be removed/cause errors.
Learn to stay away from those, <?php and echo are your friends.
( )Ben Griffiths September 11th
Nice article, good little series so far
( )Snorri3D September 11th
NICE! Keep this up this is good stuff for newbies in php as me
THANKS!
( )Erik September 11th
Nice one, but like others already said: do _NOT_ use the shorthand “<?=”, as tempting as it may seem. They are depricated as of PHP6, and a lot of servers running PHP5 don’t support them either (by default). Set up your editor to insert a snippit (like: ), to make it easier on yourself.
( )Erik Reagan September 11th
A number of you have brought up an excellent point that I failed to acknowledge. While PHP has many settings that are customizable I was assuming certain setting for certain lines of code. The last place one should write setting-specific code is in a “intro to” tutorial. Also – I was unaware that PHP 6 will be deprecating the shorthand <?=…?>.
On a similar note I have no idea how the <? … ?> go in there. I never code with that but somehow I did that in the tutorial. My apologies there.
My primary reason for working with the shorthand <?php foreach(…) : ?> … <?php endforeach; ?> was to familiarize that code with those who may look at WordPress code down the road.
( )sinned September 11th
@shane yeah thats what i mean. and im sorry guys for posting two consecutive comment.
( )Ben Griffiths September 12th
Hi @Erik – is there anywhere that shows the changes including the removal of < ? =, I can find lots of changelogs for PHP6, but nothing that mentions that shortcode being removed…
( )David Smith September 12th
Hi,
Great article for newbees. Please can you do a article on OOP in PHP. Start really simple and build towards practical examples.
How about article on using PHP with MYSQL?
Thanks
( )ahnShev September 12th
That will be very useful for me. thanx
( )Kivoiam September 12th
Awesome! Thanks for the building of a great Foundation.
( )Dainis Graveris September 12th
Thanks for the second part about PHP!
( )Appreciated! Kep up the good work!
BroOf September 12th
very useful tutorial! Please more of this kind! Love it!
( )Lostkore September 12th
Wish someone had done something as clear as this when i started learning PHP.
( )Thank you for taking time to make this.
Preben September 12th
Hi, I would recommend to watch Phpvideotutorials.com – there’s lots of very good free video tutorials there to watch. Anyway, this tute is also good!
( )Benjamin David September 12th
Nice article, thanks !
( )Maicon September 14th
Well learned. Continue please.
( )David Tucker September 14th
Great tutorial man! I think this information is perfect for people that are new to PHP.
( )Estudigital September 15th
Great and usefull!
( )Kai C September 17th
Thanks!! learned a lot from this tutorial
( )John September 24th
Arrays are very useful, thanks a lot.
( )Dennis October 1st
Great!
( )Dennis October 1st
I want to see part 3:>
( )Dennis October 1st
I want to see part 3:> when ?
( )sean steezy October 2nd
hey, this was awesome, but like the dude, above, I am eager to see the next part. take your time so I hope it will be as good as the previous two!
thanks!!!
( )Erik Reagan October 11th
Sorry part 3 is taking so long. My life is insane right now with my daughter in the hospital (born premature). She should be home really soon and when she is I’ll complete the series while I’m off work and get this ball rolling again. Thanks for the patience everyone!
( )ericb October 17th
thanks for the follow up, erik, looking forward to this series since i’m just starting to learn PHP! congrats on your new baby!
( )mike October 28th
Our CEO
Any idea why that code wouldn’t be working for me? I have it setup the exact same way, I am getting no errors, but it is not displaying the results from that part of the array.
( )mike October 28th
“”
that’s the part that isn’t working for me
( )mike October 28th
$company['staff'][0]['name']
geez…sorry. this part here.
( )mike October 28th
the foreach at the end isn’t working for me either, i am getting: “Warning: Invalid argument supplied for foreach()”
( )honour chick November 3rd
thanks alot… i still have a long way to go though. hope you continue with the tutorials
( )Alex November 12th
great stuff, as previously stated <? shorthand tags are to be avoided as they dont work with php 5, i used to get it working
( )igmuska November 19th
Awesome tutorial, short and to the point…looking forward to more
( )Steve November 24th
When coding, what’s best practice? What “rule of thumb” do you guys use for using an apostrophe versus quotes?
( )mike December 2nd
Quickly approaching the 3 month mark since part 2 was published, is there a part 3 on the horizon?
( )MMA Video Clips December 2nd
I hope part 3 is coming as well. This was an excellent example for arrays. One thing i noticed amongst alot of i different php frameworks is there strong use of arrays. I think this is one of the most important concepts that one should know with php.
Thanks again for a great tutorial.
( )mike December 2nd
I agree, I have been told by many developers that arrays are something you should have a very solid understanding of.
( )Vinay Vidyasagar December 10th
good stuff but the coding with short forms worries me coz it confuses the first time readers and its generally not a good practice. atleast thats what my mentors have taught me :0 cheers. waiting for part 3
( )Politifragilistic January 13th
Great tutorial! Short and to the point
( )Paul February 17th
Thanks for the tutorial… I would love if you could put out part 3 and beyond.
( )Jeffrey Way February 18th
@Paul – Take a look at the “Diving into PHP” video series at blog.themeforest.net.
( )codex73 March 4th
Where is part one?
( )Andres Felipe July 12th
this tutorials are so freaking awesome!! I’m just a student of interactive design whos learning PHP, and actually I don’t really need it right now but I know I will use it some day.
I have tried to find a great tutorial that treaches me PHP but it’s been an unsuccessful quest. So thank for this kinda tutorial made for kids like me lol!!!!! if you have any page that helps us with PHP please post it
thank you again, tuts+ have saved my life countless times.
( )medyum August 16th
Nice addition to the series… definitely for newbies, but I probably fall under that umbrella somewhere so I’m just happy to see more easy to follow tutorials out there like this. Looking forward to seeing the next pieces of this series! Thanks for the post
( )medyum November 10th
Nice tutorial. Like said before you use shorthand PHP tags in some places and full tags in other places.
( )