Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. PHPBeginner - The foreach Loop for Array Iteration

The foreach Loop for Array Iteration - Images: Japanese

Hey everyone, hope you're doing well!

This article is the final topic in the PHP Beginner series. If you've been reading from the very beginning, thank you so much for sticking with it all the way through. The author is genuinely delighted that you've read this far — hopefully it's been useful to you in some way.

So, let's dive into the foreach statement. The foreach statement is a syntax that lets you run a loop that iterates once for each element in an array.

Normally, when you think of looping through an array, the for statement comes to mind. But in PHP, where generating a clean, purely indexed array isn't always straightforward, the foreach statement gets used a whole lot. So let's get comfortable with it.

The basic syntax of the foreach statement, written with some plain English mixed in, looks like this.

foreach(array as variable){
    // Write your process here.
}

Written out more verbosely, it looks like this.

foreach(the array to iterate over as a variable that temporarily holds each element's value){
    // Write your process here.
}

Let's break it down. First, you write foreach, followed by (). Inside that (), you put the array to iterate over and a variable that temporarily holds the value of each element pulled from the array, separated by as. The array goes on the left side of as, and the variable goes on the right.

Here's what it looks like with actual code. We'll borrow some Vocaloid names for the sample data.

<?php
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

foreach($vocaloids as $val){
    echo $val;
}

In this case, the array vocaloids has 3 elements. So the foreach statement runs 3 times. On each iteration, the value of each element — Hatsune Miku, IA, Kagamine Rin — gets stored in the variable val. Running this produces the following output.

Hatsune MikuIAKagamine Rin

All good so far? In PHP, the order of array elements is always guaranteed, so whether it's an indexed array or an associative array, it processes them in order without fail.

Now, if you want to also pull out the key (index) of each element during the loop, you use => like this.

foreach(array as variable for the key => variable for the value){
    // Write your process here.
}

This lets you retrieve the key (index) as well. Let's modify the previous code — take a look at the following.

<?php
$vocaloids[] = 'Hatsune Miku';
$vocaloids[] = 'IA';
$vocaloids[] = 'Kagamine Rin';

foreach($vocaloids as $key => $val){
    echo 'Key \'' . $key . '\' of array \'vocaloids\' is \'' . $val . "'.\n";
}

Running this produces the following output.

Key '0' of array 'vocaloids' is 'Hatsune Miku'.
Key '1' of array 'vocaloids' is 'IA'.
Key '2' of array 'vocaloids' is 'Kagamine Rin'.

The same approach works with associative arrays too. Check out the sample below.

<?php
$vocaloids['miku'] = '080-xxxx-1234';
$vocaloids['IA'] = '090-yyyy-1234';
$vocaloids['rin']  = '080-zzzz-1234';

foreach($vocaloids as $key => $val){
    echo 'Key \'' . $key . '\' of array \'vocaloids\' is \'' . $val . "'.\n";
}

Running this produces the following output.

Key 'miku' of array 'vocaloids' is '080-xxxx-1234'.
Key 'IA' of array 'vocaloids' is '090-yyyy-1234'.
Key 'rin' of array 'vocaloids' is '080-zzzz-1234'.

One common mistake is swapping the key (index) and the value by accident. That said, it's the kind of error you'll notice pretty quickly, so there's nothing to worry too much about — just swap them back when you catch it.

Now, let's get some practice in by rewriting the "A Day in the Life of Some Guy" website we built a little while back — this time, needlessly using an array and a 'foreach statement'.

First, we'll define an array and stuff it with messages for each hour. When date() returns a single-digit hour using H, it pads it with a leading zero (like 07), giving us values from 00 to 23 — so we'll define our keys to match that.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );
?>
</body>
</html>

Next, we use 'time()' to get the current UNIX time and format it with 'date()'. In the previous article we used 'intval()' to convert the string returned by 'date()' into a number — but this time we're doing a string-to-string comparison, so that's not necessary.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );

    $time = time(); // Store the current UNIX time in a variable.
    $chr_h = date('H', $time); // Since we're comparing strings, we can assign this directly as-is.
?>
</body>
</html>

Next, let's output the current access time inside a p element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );

    $time = time(); // Store the current UNIX time in a variable.
    $chr_h = date('H', $time); // Since we're comparing strings, we can assign this directly as-is.

    echo '<p>Access time: ' . date('H:i:s', $time) . '</p>'; // Output the access time inside a p element.
?>
</body>
</html>

Next, we output the opening and closing tags for the message p element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );

    $time = time(); // Store the current UNIX time in a variable.
    $chr_h = date('H', $time); // Since we're comparing strings, we can assign this directly as-is.

    echo '<p>Access time: ' . date('H:i:s', $time) . '</p>'; // Output the access time inside a p element.

    echo '<p>'; // Output the opening tag of the message p element.

    echo '</p>'; // Output the closing tag of the message p element.
?>
</body>
</html>

Now the only thing left is to build the logic that outputs the message corresponding to the current hour. Let's use the foreach statement we just learned — needlessly — to do the comparison.

Let's pull out just the foreach statement part and walk through it.

The associative array messages holds messages for each hour as its elements. That means we can compare the variable chr_h, which holds the current hour as a string, against the keys of the associative array messages, and output the message when there's a match.

First, let's write out the foreach statement.

foreach(){

}

Now let's write it so it loops through the associative array messages. We'll have it receive the key and value in variables key and val.

foreach($messages as $key => $val){

}

Then we add logic to compare variable chr_h with variable key, and output variable val when they match.

foreach($messages as $key => $val){
    if($chr_h === $key) echo $val; // If variable 'chr_h' and variable 'key' match, output variable 'val'.
}

Now, one thing to watch out for here. When you pull out the keys of an associative array in PHP, there's a quirky interesting behind-the-scenes behavior: if a key can be interpreted as a decimal integer, PHP silently converts it to a number.

Let's experiment. We'll modify the foreach statement from above to output variable key using var_dump().

<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );

foreach($messages as $key => $val){
    var_dump($key);
}

Running this produces the following output.

string(2) "00"
string(2) "01"
string(2) "02"
string(2) "03"
string(2) "04"
string(2) "05"
string(2) "06"
string(2) "07"
string(2) "08"
string(2) "09"
int(10)
int(11)
int(12)
int(13)
int(14)
int(15)
int(16)
int(17)
int(18)
int(19)
int(20)
int(21)
int(22)
int(23)

'00' through '09' come back as strings, but '10' through '23' — which can be interpreted as decimal numbers — come back as integers.

So if you want to do a strict comparison, you need to convert variable key to a string to match variable chr_h. Let's use strval() to convert variable key to a string.

foreach($messages as $key => $val){
    if($chr_h === strval($key)) echo $val; // If variable 'chr_h' matches variable 'key' converted to a string, output variable 'val'.
}

That does it. Now let's plug this into the HTML source from earlier. Here's the finished product.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );

    $time = time(); // Store the current UNIX time in a variable.
    $chr_h = date('H', $time); // Since we're comparing strings, we can assign this directly as-is.

    echo '<p>Access time: ' . date('H:i:s', $time) . '</p>'; // Output the access time inside a p element.

    echo '<p>'; // Output the opening tag of the message p element.

    foreach($messages as $key => $val){
        if($chr_h === strval($key)) echo $val; // If variable 'chr_h' matches variable 'key' converted to a string, output variable 'val'.
    }

    echo '</p>'; // Output the closing tag of the message p element.
?>
</body>
</html>

Click here for the sample.

That's basically how the foreach statement works. It's not the most elegant solution, but it gives you a good feel for how to use it. It's a very commonly used syntax, so make sure you've got it down solid.

By the way, if you're confident the associative array is properly defined and no validation is needed, the message output part can actually be written in a single line.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Day in the Life of Some Guy</title>
</head>
<body>
<?php
    $messages = array(
        '00' => '....',
        '01' => '....',
        '02' => '....',
        '03' => '....',
        '04' => '....',
        '05' => '....',
        '06' => '....',
        '07' => '....',
        '08' => 'Woke up. A bit hungover but functional. Going full throttle right away might burn me out, so I\'ll start with coffee and ease into the day. Getting serious at 9.',
        '09' => '....',
        '10' => '....',
        '11' => 'Oops. I was watching videos and a few hours just disappeared. But it\'s not time to panic yet. Getting serious at 12.',
        '12' => 'It\'s lunchtime for the world. I\'m getting hungry too. Hate to miss the satisfying milestone of noon, but syncing up with the flow of society is very important. Plenty of day left. I\'ll grab lunch first. Getting serious at 1.',
        '13' => '....',
        '14' => '....',
        '15' => 'Oops. Ate a big meal and somehow dozed off. But jumping straight into work right after waking up is bad for you. Plenty of day left. Getting serious at 4.',
        '16' => 'Feeling sluggish after that nap. Pushing through won\'t help, so this is a time for patience. The night is still young. Getting serious at 5.',
        '17' => '....',
        '18' => '....',
        '19' => '....',
        '20' => '....',
        '21' => 'Oops. Was playing games and look at the time. It\'s not too late to work, but it\'s also dinner hour for the world. Syncing up with the flow of society is very important. I\'ll grab dinner first. Getting serious at 10.',
        '22' => '....',
        '23' => 'Oops. Was drinking beer and it got this late. Very unfortunate — today just wasn\'t my chance. Consoling myself by posting "Today was a productive day" online. Getting serious tomorrow.'
    );

    $time = time(); // Store the current UNIX time in a variable.
    $chr_h = date('H', $time); // Since we're comparing strings, we can assign this directly as-is.

    echo '<p>Access time: ' . date('H:i:s', $time) . '</p>'; // Output the access time inside a p element.

    echo '<p>' . $messages[$chr_h] . '</p>'; // This alone is actually all you need.
?>
</body>
</html>

Click here for the sample.

Finding more efficient ways to write and handle things like this is one of the fun parts of programming.

And with that, the PHP Beginner series comes to a close. Thank you so much for reading all the way through. The next article is a full summary, so if there's anything you've forgotten, feel free to check it there.

Take care, and see you next time!

This article was written by Sakurama.

Author's beloved small mammal

桜舞 春人 Sakurama Haruto

A Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him.

If you find any errors or copyright issues, please .