3 ways to render inline lists in PHP

Given a list of items and a separator, render it in a single line, with separators between.

1
2
3
4
5
6
7
$items = [ 
    "apples",
    "oranges",
    "bananas"
];

$separator = " / ";

Method 1: Basic foreach

This approach is the one that comes to mind first, but it is incorrect because it will emit an additional separator after the last element.

1
2
3
foreach ($items as $value) { 
    echo $value . $separator;
}

Output:

1
apples / oranges / bananas /

Method 2: Using implode()

Cleaner and shorter, this usage is appropriate for most applications:

1
echo implode($separator, $items);

Output:

1
apples / oranges / bananas

While the implode() method is great for most purposes, it does break down when there is heavy templating involved.

Method 3: Using foreach and

When heavier templating functionality is required, it’s best to use

1
2
3
4
5
6
7
foreach ($items as $key => $value) {
    echo $value;

    if ($key !== array_key_last($items)) {
        echo $separator;
    }
}

The third method has the same output as the second one, but gives you more flexibility in how you might organize your templates.

Read Next

I’m running an experiment for better content recommendations. These are the 3 posts that are most likely to be interesting for you:

Licensed under CC BY-NC-SA 4.0
All content is licensed under CC BY-NC-SA 4.0. Copying is an act of love - please copy!
More cool websites: Prev | Hotline Webring | Next
Built with Hugo
Theme Stack designed by Jimmy