November 19, 2026 - 11:04
PHP Lesson 02 — List Tasks with Arrays and foreach Image
PHP Tutorials

PHP Lesson 02 — List Tasks with Arrays and foreach

0 Comments

Print two tasks by hand

Last time we put a heading on the page. Add these two entries in public/foreach-demo.php. Start PHP from the project folder with php -S 127.0.0.1:8000 -t public, then open http://127.0.0.1:8000/foreach-demo.php. The square brackets make an array. The first item has index 0 and the second has index 1.

PHP
<?php
$tasks = ['Read the lesson', 'Run the example'];
?>
<ul>
  <li><?= htmlspecialchars($tasks[0], ENT_QUOTES, 'UTF-8') ?></li>
  <li><?= htmlspecialchars($tasks[1], ENT_QUOTES, 'UTF-8') ?></li>
</ul>

Add a third item

Append a third title to the array and refresh. You still get two rows because the HTML only references the first two items. Replace the file with this version and refresh again.

PHP
<?php
$tasks = ['Read the lesson', 'Run the example', 'Add a third task'];
?>
<ul>
<?php foreach ($tasks as $task): ?>
  <li><?= htmlspecialchars($task, ENT_QUOTES, 'UTF-8') ?></li>
<?php endforeach; ?>
</ul>

Read it one item at a time

Read foreach ($tasks as $task) as ‘take each item from $tasks and call it $task for this turn.’ Each turn creates one list item. Try an empty array and the loop runs zero times. If you need only the first item, check that index 0 exists and read it directly. Use for when the job is to repeat a fixed number of times, and while when an ongoing condition decides when to stop.

Give each task a status

Imagine two notes on each task card, one for the title and another for whether it is done. Each entry is now its own array. The title key holds text and done holds true or false. Switch the second task to true in the full example and refresh. Only its status changes.

Complete working files

Below is the complete working version for this lesson. Save each file at the path in its heading. If you are continuing from the previous lesson, replace the matching files.

public/index.php
PHP
<?php
declare(strict_types=1);

function e(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}


$tasks = [
    ['title' => 'Read the lesson', 'done' => true],
    ['title' => 'Run the example', 'done' => false],
];
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Task list</title>
<h1>Task list</h1>
<?php if ($tasks === []): ?><p>No matching tasks.</p><?php endif; ?>
<ul>
<?php foreach ($tasks as $task): ?>
  <li>
    <?= e($task['title']) ?> — <?= $task['done'] ? 'Completed' : 'Pending' ?>
  </li>
<?php endforeach; ?>
</ul>
</html>

After saving the files, run php -S 127.0.0.1:8000 -t public in the project folder and open http://127.0.0.1:8000/. If the server is already running from that project folder, refresh the page.

PHP htmlspecialchars

Related Articles

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment