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.

15 Comments

  1. Jem

    16 Jun 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. Foreach and array both are functions that haven’t come easily for me. Thanks for the helpful explanation. :)

  3. 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. 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. 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. You are amazing :D

    Yay, I think I can learn PHP now :D

  7. 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. 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. 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. 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. 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. 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. […] 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. I can’t believe I forgot to tell you thank you.

    Thank you Jem.

  15. 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!