Beginner’s Guide to PHP – Part Four

In Part Three of the Beginner’s Guide to PHP we learnt about the if construct (“statement”), and using it to check the value of some input. In this guide we’ll learn about two more constructs: foreach() and array()

foreach Construct

foreach — a type of loop, but we’ll cover that more in the future — is a language construct created to easily iterate through arrays. Iterate is simply a posh word for doing something repeatedly; in this context, iterate refers to the process of executing a given instruction for each value in the array. foreach has two different valid syntax, similar in style but both useful in different situations:

foreach($array as $value)
	do this statement

foreach($array as $key => $value)
	do this statement

However, to understand foreach properly, first we need to understand arrays…

Understanding Arrays

When I was first learning PHP, it took me longer to come to grips with arrays than anything else (no idea why), so I hope that I’ll be able to explain them to you without putting you all in the same predicament. An array is like a bank of values. Where a variable only stores one bit of information (e.g. <?php $variable = "data"; ?>) an array stores multiple bits — sometimes other arrays — with each value (bit of info) assigned to its own key.

Creating and Populating Arrays

An array is usually created with the array construct, like so:

<?php
$array = array();
?>

We can then populate the array with data. The easiest way of doing this is creating a comma separated list of the values we want to store inside the array(), like so:

<?php
$array = array("value", "data", "information", "stuff");
?>

When using this method, each bit of data is assigned a numerical key starting from 0 — so key 0 would contain value, 1 would contain data and so on — thus ideal for storing data that doesn’t need specific keys.

Sometimes, however, we need a nice logical key for each bit of information stored. For example, let’s take fast food (a subject close to my heart ;) ). We have burgers, pizzas and steak. Let’s imagine that we need to store the restaurant name for each of these types of fast food, so that we can show the restaurant name without having to remember numerical keys. The data would be inserted into the array like so:

<?php
$fastfood = array(
	"burgers" => "McDoogles", 
	"pizza" => "Pizza Barn", 
	"steak" => "Joe's Steak House"
	);
?>

..where the desired key is specified, followed by => and then the required value. Each key/value pair is separated by a comma. I’ve spaced it all out in the example to make it easier to read, but there’s no reason why you can’t specify the data without gaps as per our numerical key array (e.g. $fastfood = array("burgers" => "McDoogles", "pizza" => "Pizza Barn", "steak" => "Joe's Steak House"); )

Back to foreach

We now have a useful array storing fast food types and the name of the restaurant associated with this food. Using echo, which we learnt about in Part Two, we could echo each bit of information from the array separately addressing it by key (e.g. echo $array['key'] where array is the name of the array, and key is .. well, the key)

…or we could go one better and use foreach to iterate over the array and echo each key/value pair automatically. This has the advantage that if we add to the array, the new data will be echoed without us having to manually add more echo statements.

To do this, we use the second foreach syntax demonstrated above (we could use the first, but wouldn’t have easy access to the array key, which we need). We want to loop over the $fastfood array, echo the key (which contains our fast food type) and the value (which contains the name of the restaurant where this is available). The code for this is as follows:

foreach($fastfood as $key => $value)
	echo $key . ' is available at: ' . $value . '<br>';

Put together with our earlier code:

<?php
$fastfood = array(
	"burgers" => "McDoogles", 
	"pizza" => "Pizza Barn", 
	"steak" => "Joe's Steak House"
	);

foreach($fastfood as $key => $value)
	echo $key . ' is available at: ' . $value . '<br>';
?>

This would give us the following output:

burgers is available at: McDoogles
pizza is available at: Pizza Barn
steak is available at: Joe’s Steak House

Excusing the grammatical error, we have an accurate list of fast food and the restaurant it is available from.

Just like the if construct, if we wanted to add more than one statement to execute inside the foreach, we can use curly braces:

foreach($array as $key => $value) {
	do statement 1;
	do statement 2;
}

And that, my dears, is foreach. Feel free to ask any questions you may have :)

Important note: in the code example I use a full stop to concatenate variables to the string within the single quotation marks. I haven’t covered this in detail yet, but will get to it in one of my future guides.

php beginner's guideThis article is part of the Beginner’s Guide to PHP series. You can see all the guides or jump to Part Five.
affiliate window advert

17 comments so far

  1. Jem said:
    On June 16, 2008 at 5:06 pm

    Authors note (teehee): I tried to make this guide as simple as possible given the subject, but in doing so have missed out a few bits on foreach and loops in general. I don’t think this will necessarily affect the quality of the information but may make some of you php programmers antsy? ;) If you feel you have anything to add — or can think of better ways to word what I’ve put — please feel free to contribute :D

  2. Hannah said:
    On June 16, 2008 at 5:38 pm

    Foreach and array both are functions that haven’t come easily for me. Thanks for the helpful explanation. :)

  3. barbilee said:
    On June 16, 2008 at 7:53 pm

    i have wanted to learn how to write something like the scripts you do but i think i need to know more about coding. like i togth it was gonna be hard to do php includes and i always got over welled with tuts in it and such and just one day i said to my self fuck it in 3 mins i had it. maybe thats my mind felling over welling lolz i dont know maybe thats something i try one day but its a wonderful tut thanks.

  4. Stephanie said:
    On June 16, 2008 at 7:56 pm

    Very well written. I think you did a very good job explaining arrays. They were the one thing I actually understood while taking my class on C, but a lot of people were left scratching their heads. It was pretty much hit or miss with understanding our professor.. he was a bit of a loon. But yeah. I think your guide is coming along fantastically. Maybe when I actually can stomach programming again, I’ll find all the guides and read them in one blow and see what I can do.

  5. Clem said:
    On June 16, 2008 at 8:51 pm

    Thanks, Jem. I’m trying to learn basic PHP, and it’s a little confusing for me. I was right up to here in all the other tutorials, but I just couldn’t quite seem to wrap my head around it. I think I kind of get it now. :P

  6. Shen-Shen said:
    On June 16, 2008 at 8:58 pm

    You are amazing :D

    Yay, I think I can learn PHP now :D

  7. Vanesa said:
    On June 16, 2008 at 10:09 pm

    Thanks for these guides! ^^ They really are easy, and reading them over a couple of times gives me a basic idea of how everything works. I recognize some of this while looking at scripts.

    You’re the best! :)

  8. Steven said:
    On June 16, 2008 at 11:21 pm

    Thank you for the helpful post Jem! I never understood loops even though I consider myself a PHP veteran. :P Could you give me/us some examples where we could use foreach loops in a practical script? For instance, is a foreach loop to print out a bunch of blog entries better than a while loop?

  9. Vasili said:
    On June 17, 2008 at 12:00 am

    This would have helped back when I had no clue how to use foreach :P I think multidimensional arrays are very annoying to work with in foreach statements.

    I personal bookmarked the array page in php.net because some of the functions are very helpful and I’ve never heard of them before! (http://php.net/array)

  10. Michelle Potter said:
    On June 17, 2008 at 12:25 pm

    Thank you so much for this explanation! Just yesterday I was writing a little script where I needed to do exactly this. I knew there was a way to do what I wanted with arrays, but I have never understood them, so I hacked a very inelegant workaround. Using this tutorial I took 10 lines of code down to 3 lines — much better!

  11. Carly said:
    On June 17, 2008 at 1:10 pm

    I get paid at work to sit and learn stuff like this – might sit down for an hour or two and read through all your guides.

    Thanks jem

  12. Rosamunda said:
    On June 29, 2008 at 4:05 pm

    I´m “in the process” of learning PHP. And I can say that arrays are damn difficult to understand.
    Thanks for your time and excellent explanation! Please continue this good job!
    Cheers from Buenos Aires!
    Rosamunda

  13. Beginner’s Guide to PHP - Part Five — jemjabella.co.uk said:
    On September 19, 2008 at 8:44 pm

    […] in Part Four of the Beginner’s Guide to PHP, we covered the basics of arrays, and the foreach construct which is used to iterate over arrays. […]

  14. Hev said:
    On September 20, 2008 at 12:31 am

    I can’t believe I forgot to tell you thank you.

    Thank you Jem.

  15. Veronica said:
    On August 7, 2009 at 2:00 am

    foreach($array as $value)
    do this statement

    I'm currently teaching myself how to code WordPress. haha! So far by reading the Codex over and over and using your guides on the side to explain the PHP functionality better, I am catching on quickly! I fully understand this tutorial! Thanks! However, could you please elaborate on the meaning of "as" in the foreach() function above? Just a wee bit? ^_^

    Thanks, Jem! You are an amazing PHP teaching goddess!