ArchivesPHP and MySQLi Tutorials of

PHP Tutorial: foreach() lock there is a key

When programming in PHP you will often find yourself using arrays. But what if you have a large array, with 50 items? How can you access the data stored in it without having to type each key? You can send the array through a foreach(). What a foreach() does is executes a block of code for each item in an array. There are two ways to use a foreach(), once is to use only the values, and the other is to use both keys and values. I’ll start with the values only way.

/* our array */
$media = array('Vinyl','8-Track','Cassette','Compact Disc');
?>My Favourite media types are:<ol><?php
/* so foreach item in $media, give the $value */
foreach ( $media as $value ) {
    echo "<li>$value</li>\n";

This should yield:

My Favourite media types are:

   1. Vinyl
   2. 8-Track
   3. Cassette
   4. Compact Disc

“Ok Mike, got it, but what about my keys?” Right, keys, well using your keys in a foreach() is also a very common method. Here is how it is done:

/* our array */
$media = array(
4=>'Compact Disc');
?>My Favourite media types are:<br /><?php
/* so foreach item in $media, give me the 
key as $key and the value as $value */
foreach($media as $key => $value) {
    echo "$key: $value<br />\n";

This should yield:

My Favourite media types are:
1: Vinyl
2: 8-Track
3: Cassette
4: Compact Disc

Now, obviously this is a very simple example, but it gives you the basics how to to initiate a foreach() loop. I hope you found this useful.

By Mike on March 29, 2011 | PHP, Tutorials
Tags: , , ,