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.

<?php
/* 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";
}
?></ol>

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:

<?php
/* our array */
$media = array(
1=>'Vinyl',
2=>'8-Track',
3=>'Cassette',
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.

Author: Mike on March 29, 2011
Category: PHP, Tutorials
Tags: , , ,

One thought on “PHP Tutorial: foreach() lock there is a key”

  1. Sarah E says:

    With all these silly websites, such a great page keeps my internet hope alive.

Comments are closed.

Last articles