Dynamic HTML with PHP Loops
Generate HTML tables and lists from PHP arrays inside templates.
Dynamic HTML with PHP Loops is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
PHP-Driven HTML Generation
One of PHP's most powerful uses is generating HTML dynamically from data arrays — lists, tables, dropdowns, navigation menus, and more.
Generating a List
Render an HTML unordered list from a PHP array:
<?php
$fruits = ['Apple', 'Banana', 'Cherry', 'Durian'];
?>
<ul>
<?php foreach ($fruits as $fruit): ?>
<li><?= htmlspecialchars($fruit) ?></li>
<?php endforeach; ?>
</ul>Generating an HTML Table
Build a dynamic table from a 2D array:
<?php
$users = [
['Alice', 'alice@test.com', 'Admin'],
['Bob', 'bob@test.com', 'User'],
];
?>
<table>
<thead><tr><th>Name</th><th>Email</th><th>Role</th></tr></thead>
<tbody>
<?php foreach ($users as [$name, $email, $role]): ?>
<tr>
<td><?= htmlspecialchars($name) ?></td>
<td><?= htmlspecialchars($email) ?></td>
<td><?= htmlspecialchars($role) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>Generating a Select Dropdown
Build an HTML select element from an array:
<?php
$countries = ['TR' => 'Turkey', 'US' => 'United States', 'DE' => 'Germany'];
$selected = 'TR';
?>
<select name="country">
<?php foreach ($countries as $code => $name): ?>
<option value="<?= htmlspecialchars($code) ?>"
<?= $code === $selected ? 'selected' : '' ?>>
<?= htmlspecialchars($name) ?>
</option>
<?php endforeach; ?>
</select>Zebra Striping Rows
Apply alternating row styles for readability:
<?php
$rows = range(1, 8);
?>
<table>
<?php foreach ($rows as $i => $row): ?>
<tr class="<?= $i % 2 === 0 ? 'even' : 'odd' ?>">
<td>Row <?= $row ?></td>
</tr>
<?php endforeach; ?>
</table>Conditional CSS Classes
Apply CSS classes based on data conditions:
<?php
$tasks = [
['title' => 'Write tests', 'done' => true],
['title' => 'Deploy app', 'done' => false],
];
?>
<ul class="task-list">
<?php foreach ($tasks as $task): ?>
<li class="task <?= $task['done'] ? 'done' : 'pending' ?>">
<?= htmlspecialchars($task['title']) ?>
</li>
<?php endforeach; ?>
</ul>Pagination Links
Generate pagination UI from a for loop:
<?php
$totalPages = 10;
$currentPage = 3;
?>
<nav class="pagination">
<?php for ($p = 1; $p <= $totalPages; $p++): ?>
<a href="?page=<?= $p ?>"
class="<?= $p === $currentPage ? 'active' : '' ?>">
<?= $p ?>
</a>
<?php endfor; ?>
</nav>Nested Loops for Nested HTML
Generate nested HTML structures with nested loops:
<?php
$menu = [
['Home', '/', []],
['Products', '/products', ['Widgets', 'Gadgets']],
['About', '/about', []],
];
?>
<ul>
<?php foreach ($menu as [$label, $href, $sub]): ?>
<li><a href="<?= $href ?>"><?= htmlspecialchars($label) ?></a>
<?php if ($sub): ?>
<ul>
<?php foreach ($sub as $child): ?>
<li><?= htmlspecialchars($child) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>Empty State Handling
Always handle the empty array case in templates:
<?php
$posts = [];
?>
<?php if (!empty($posts)): ?>
<ul>
<?php foreach ($posts as $post): ?>
<li><?= htmlspecialchars($post['title']) ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p class="empty-state">No posts found. <a href="/new">Create one!</a></p>
<?php endif; ?>Generating Data Attributes
Pass data to JavaScript via HTML data attributes:
<?php
$products = [
['id' => 1, 'name' => 'Widget', 'price' => 9.99],
['id' => 2, 'name' => 'Gadget', 'price' => 24.99],
];
?>
<div class="product-grid">
<?php foreach ($products as $p): ?>
<div class="product-card"
data-id="<?= $p['id'] ?>"
data-price="<?= $p['price'] ?>">
<?= htmlspecialchars($p['name']) ?>
</div>
<?php endforeach; ?>
</div>PHP and JSON for JavaScript
Pass PHP arrays to JavaScript safely using json_encode:
<?php
$config = [
'apiUrl' => '/api/v1',
'userId' => $user['id'] ?? 0,
'locale' => 'en-US',
];
?>
<script>
const APP_CONFIG = <?= json_encode($config, JSON_HEX_TAG | JSON_HEX_APOS) ?>;
console.log(APP_CONFIG.apiUrl);
</script>Quick Check
Which function must you use when outputting user-controlled strings inside HTML to prevent XSS?
Recap: Dynamic HTML with Loops
Key techniques:
- Use alternative foreach/for colon syntax in templates
- Always escape output with
htmlspecialchars() - Conditional CSS classes with ternary in attributes
- Handle empty arrays with if/else around loops
- Pass PHP data to JavaScript via
json_encode()
Frequently asked questions
Is the “Dynamic HTML with PHP Loops” lesson free?
Yes — the full text of “Dynamic HTML with PHP Loops” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Dynamic HTML with PHP Loops”?
Generate HTML tables and lists from PHP arrays inside templates. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Dynamic HTML with PHP Loops” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- PHP Tags and Embedding Syntax
- Dynamic HTML with PHP Loops
- Including and Requiring Files
- Template Pattern: Separating Logic from View