[PHP for Beginners] How to Dynamically Display a News/Notice List with a foreach Loop
You often see "News" or "Notices" lists on websites, right? It's a hassle to manually update the HTML every time new information is added. Actually, by using PHP's foreach loop, you can automate this tedious task and easily create a dynamic list that always displays the latest information.
In this article, we'll explain the basics and applications of PHP's `foreach` loop using a practical notice list example, so even programming beginners can experience getting it to "just work" by simply copying and pasting. Let's master the flow of taking data stored in an array one by one and displaying it as an HTML list together!
To get your PHP running (development environment), if you haven't set up XAMPP yet, please refer to [PHP for Beginners] A Complete Guide to Downloading and Installing XAMPP!. After installation, place your PHP file in the specified folder (like `htdocs`), and you're all set!
1. The Absolute Basics! PHP Arrays and the foreach Loop
First, to understand what `foreach` does, let's start with its partner, the "array."
An array is like a box that can store multiple values together. For example, if you want to manage notice information as sets of "date" and "title," you can create an array like this:
<?php
// Array storing the news information
$news_items = [
[
"date" => "2025-07-03",
"title" => "Notice of Summer Holiday Closure"
],
[
"date" => "2025-07-01",
"title" => "Launched New Service 'γγ'"
],
[
"date" => "2025-06-20",
"title" => "Our Website Has Been Renewed"
]
];
// Check the contents of the array (for debugging)
print_r($news_items);
?>
The job of the `foreach` loop is to take items out of this "box" called an array one by one and process them. The syntax is very simple:
foreach (array as $variable_for_temporary_element) { ...processing... }
Using this syntax, let's try to take out just the titles from the previous array in order and display them.
<?php
$news_items = [
["date" => "2025-07-03", "title" => "Notice of Summer Holiday Closure"],
["date" => "2025-07-01", "title" => "Launched New Service 'γγ'"],
["date" => "2025-06-20", "title" => "Our Website Has Been Renewed"]
];
// Take out each notice from the array one by one
foreach ($news_items as $item) {
// Display the title of the notice that was taken out
echo $item['title'] . "\n";
}
?>
As you can see, `foreach` automatically repeats the process until there are no more elements left in the array. This is the heart of dynamic list generation.
2. In Practice! Creating a Notice List with foreach
Now for the main event. Let's use the array and `foreach` loop from before to create a notice list in HTML format that can be displayed on a web page. The following code is the most basic form combining HTML and PHP. If you copy and paste this into a file, you can view it in your browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Notice List</title>
<style>
body { font-family: sans-serif; line-height: 1.6; padding: 20px; }
.news-list { list-style: none; padding: 0; border-top: 1px solid #ccc; }
.news-list li { padding: 15px 10px; border-bottom: 1px solid #ccc; }
.news-date { font-weight: bold; margin-right: 1em; color: #555; }
</style>
</head>
<body>
<h1>Notices</h1>
<?php
// Prepare the notice information as an array
$notices = [
[
"date" => "2025-07-03",
"title" => "Notice of Summer Holiday Closure"
],
[
"date" => "2025-07-01",
"title" => "Launched New Service 'γγ'"
],
[
"date" => "2025-06-20",
"title" => "Our Website Has Been Renewed"
]
];
?>
<ul class="news-list">
<?php foreach ($notices as $notice): ?>
<li>
<span class="news-date"><?php echo htmlspecialchars($notice['date']); ?></span>
<span class="news-title"><?php echo htmlspecialchars($notice['title']); ?></span>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>
The key point of this code is that the `foreach` loop runs inside the `
- ` tags. For each piece of data stored in the `$notices` array, one set of `
- ` tags is generated. If you increase the number of elements in the array to four or five, the list items will automatically increase as well. This is how "dynamic list generation" works.
3. Making It More Convenient with Applied Examples
Now that you understand the basics, let's modify it into a more practical form.
Adding Links to Each Notice
A notice list isn't complete without links to the detail pages for each item. Let's try adding URL information to the array and modifying the loop to generate `<a>` tags.
<ul class="news-list"> <?php // Array with URL information added $notices_with_links = [ [ "date" => "2025-07-03", "title" => "Notice of Summer Holiday Closure", "url" => "/news/summer-holiday.html" ], [ "date" => "2025-07-01", "title" => "Launched New Service 'γγ'", "url" => "/news/new-service.html" ] ]; foreach ($notices_with_links as $notice): ?> <li> <span class="news-date"><?php echo htmlspecialchars($notice['date']); ?></span> <a href="<?php echo htmlspecialchars($notice['url']); ?>"> <?php echo htmlspecialchars($notice['title']); ?> </a> </li> <?php endforeach; ?> </ul>
By simply wrapping the title part with an `<a>` tag and setting the `href` attribute to the URL obtained from the array, you can easily create a list with links.
Changing the Date Format
Instead of a format like "2025-07-03," you might want to display it in a friendlier format like "July 03, 2025." By combining PHP's `date()` and `strtotime()` functions, you can freely change the date format.
<ul class="news-list"> <?php $notices = [ ["date" => "2025-07-03", "title" => "Notice of Summer Holiday Closure"], ["date" => "2025-07-01", "title" => "Launched New Service 'γγ'"] ]; foreach ($notices as $notice): // Convert the date string to a timestamp $timestamp = strtotime($notice['date']); // Convert to your desired format and display $formatted_date = date("F d, Y", $timestamp); ?> <li> <span class="news-date"><?php echo $formatted_date; ?></span> <span class="news-title"><?php echo htmlspecialchars($notice['title']); ?></span> </li> <?php endforeach; ?> </ul>
Here, `strtotime()` converts the date string into a number that PHP can handle (a timestamp), and `date()` converts that number into the specified format. You can also add the day of the week by using a format like `"l, F d, Y"`.
4. Points to Be Careful About
There are a few things to keep in mind when using `foreach` loops.
What if the Array is Empty?
You also need to consider cases where the source array for the loop is empty, such as when no notices have been registered yet. If the array is empty, `foreach` won't cause an errorβit will simply be skipped. However, it's more user-friendly to display a message like "There are no notices."
You can use PHP's `empty()` function to check if an array is empty beforehand.
<?php // An empty array with no notices yet $notices = []; ?> <h1>Notices</h1> <?php if (empty($notices)): ?> <p>There are currently no new notices.</p> <?php else: ?> <ul class="news-list"> <?php foreach ($notices as $notice): ?> <li> <!-- List display processing --> </li> <?php endforeach; ?> </ul> <?php endif; ?>
By using `if (empty($notices))` to write the display for when the array is empty and `else` for the list display processing when the array has data, you can create robust code that handles any situation.
The Importance of HTML Escaping
When displaying data obtained from external sources like a database on a web page, it is crucial to pass it through the `htmlspecialchars()` function as a security measure. This is to prevent Cross-Site Scripting (XSS) attacks, where malicious JavaScript code could be embedded.
Even if it's data you entered yourself, it's safe to get into the habit of always wrapping it with `htmlspecialchars()` when outputting to the screen with `echo`.
<?php // Example of data containing malicious code $notice = [ "title" => "<script>alert('XSS');</script>" ]; ?> <!-- Bad example: The script will execute if output directly --> <span><?php echo $notice['title']; ?></span> <!-- Good example: Use htmlspecialchars for escaping --> <span><?php echo htmlspecialchars($notice['title']); ?></span>
In the good example, the string "<script>alert('XSS');</script>" will be displayed as is in the browser, and the script will not be executed.
5. Summary and Introduction to Related Code
In this article, we explained how to dynamically generate a notice list from array data using PHP's `foreach` loop. This pattern is an extremely powerful technique that can be applied to all sorts of "repeated displays" on a website, not just notice lists, but also product lists, blog post lists, galleries, and more.
Once you've mastered the basic form, please try creating various list displays on your own site. If you modify the code to fetch array data from a database, it will be the first step toward a full-fledged web application.
Similar loop processes to `foreach` include the `while` loop, which continues processing as long as a condition is met. If you want to repeat something a specific number of times, the `for` loop is convenient. Understanding the characteristics of each and using them according to the situation will further broaden your programming horizons.