We enter php, linux, mysql in a box and want to show each item as a task tag. We do not have an array yet; we have one comma-separated string. Before using foreach, we need to split it into pieces.
explode() handles splitting and implode() joining. We will also decide what to do about spaces, consecutive commas, and a valid 0 tag. Create experiment.php in a new folder and run each version there with php experiment.php.
Split at each comma
<?php
$text = 'php, linux, mysql';
$tags = explode(',', $text);
foreach ($tags as $index => $tag) {
echo $index, ': [', $tag, ']', PHP_EOL;
}
The three items are [php], [ linux], and [ mysql]. The first argument is the separator and the second is the string to split. Commas are removed, but spaces after them remain. Splitting does not also trim each resulting part.
The foreach form $index => $tag gives us each item's key as well as its value, which is why we see 0, 1, and 2. Now that $tags is an array, foreach can iterate over it.
Does no comma mean an empty array?
<?php
$tags = explode(',', 'php');
var_dump(count($tags));
var_dump($tags[0]);
No: the output is int(1) and string(3) "php". Without a separator match, the entire string remains as one item. Supplying an empty separator is not a way to split into individual letters either; PHP 8 throws a ValueError for an empty separator.
Handle consecutive commas
<?php
$text = 'php, linux,,0, mysql, ';
$tags = explode(',', $text);
$clean = [];
foreach ($tags as $tag) {
$tag = trim($tag);
if ($tag !== '') {
$clean[] = $tag;
}
}
foreach ($clean as $index => $tag) {
echo $index, ': [', $tag, ']', PHP_EOL;
}
This input contains consecutive commas and a trailing comma. We trim every part, then append only parts that are not exactly an empty string to $clean. The results retain php, linux, 0, and mysql, with sequential keys from 0 to 3.
$clean[] = $tag; appends an item to the array. We do not carry the old keys into the new array, so skipping an empty part does not leave a gap. The explicit loop makes the decision about each retained value visible.
A shortcut can remove zero too
<?php
$tags = ['php', '', '0', 'mysql'];
$filtered = array_filter($tags);
foreach ($filtered as $index => $tag) {
echo $index, ': [', $tag, ']', PHP_EOL;
}
With no callback, array_filter() removes string '0' as well as the empty string. The output contains only 0: [php] and 3: [mysql]. It also preserves the original keys rather than reindexing them. This does not automatically implement our narrower “remove only empty strings” rule.
Keep the explicit loop for this example. We could later supply our own checking function to array_filter, but there is no need to hide the individual decisions while learning the rule.
Join the list into a line again
<?php
$tags = ['php', 'linux', '0', 'mysql'];
echo implode(', ', $tags), PHP_EOL;
echo implode(' | ', $tags), PHP_EOL;
The first line is php, linux, 0, mysql; the second is php | linux | 0 | mysql. Now we choose the separator to insert. implode() places its first argument between items, without adding an extra separator before the first or after the last.
Finish with a browser experiment
This complete file reads a text field, displays its tags, and joins them again. parseTags() is our helper containing the loop we just built. h() performs the HTML output encoding from the earlier lesson.
<?php
declare(strict_types=1);
function parseTags(string $text): array
{
$tags = [];
foreach (explode(',', $text) as $part) {
$tag = trim($part);
if ($tag !== '') {
$tags[] = $tag;
}
}
return $tags;
}
function h(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$raw = $_GET['tags'] ?? 'php, linux,,0, mysql';
$input = is_string($raw) ? $raw : '';
$tags = parseTags($input);
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Tag experiment</title>
<form method="get">
<label for="tags">Tags</label>
<input id="tags" name="tags" value="<?= h($input) ?>">
<button>Split</button>
</form>
<ul>
<?php foreach ($tags as $tag): ?>
<li><?= h($tag) ?></li>
<?php endforeach; ?>
</ul>
<p>Joined: <?= h(implode(', ', $tags)) ?></p>
</html>
Start php -S 127.0.0.1:8001 in the folder and open http://127.0.0.1:8001/experiment.php. Change the field and press Split. Try php,,0, <em>linux</em>: expect three tags, including zero and the literal markup text. The markup is not executed as HTML.
This is a simple tag-field format. A real CSV file can contain commas inside quoted fields and needs its own parsing rules; plain explode is not a CSV parser. Finally try , ,: the list should become empty and the joined line should contain no tags.
Where this appeared in the task list: PHP Lesson 02 — List Tasks with Arrays and foreach
Official documentation: explode · implode · array_filter · str_getcsv