Home » Php » php – Add comma between foreach looped items but not at end

php – Add comma between foreach looped items but not at end

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’d like to achieve on adding a comma between my authors in my foreach but each time I make any references, it adds a comma at the end also.

Here is what I have below:

<div class="four-sixths first">
    <a href="<?php echo 'URL' ?>"><img class="mb-20" src="<?= $recipe->get_thumbnail() ?>" alt=""/></a>
    <h2 class="mb-5"><?= $recipe->get_title() ?></h2>
    <span><?= $recipe->get_date() ?></span> -
        <?php foreach ($recipe->get_authors() as $profile): ?>
            <a href="<?= $profile->get_url() ?>"><?= $profile->get_name() ?></a>,
        <?php endforeach; ?>
    <p><?= $recipe->get_content() ?></p>
</div>

Which gives me the following results:
enter image description here

How can I prevent a comma at the end?

How to&Answers:

Since you were skeptical about implode, here’s a simple example (just showing the loop):

    <?php foreach ($recipe->get_authors() as $profile):
        $links[] = '<a href="' . $profile->get_url() . '">' . $profile->get_name() . '</a>';
    endforeach; ?>
    <?= implode(', ', $links); ?>

Answer:

An alternative using join:

<div class="four-sixths first">
    <a href="<?php echo 'URL' ?>"><img class="mb-20" src="<?= $recipe->get_thumbnail() ?>" alt=""/></a>
    <h2 class="mb-5"><?= $recipe->get_title() ?></h2>
    <span><?= $recipe->get_date() ?></span> - <?= join(", ", array_map(function ($profile) { return sprintf('<a href="%s">%s</a>', $profile->get_url(), $profile->get_name()); }, $recipe->get_authors())) ?>
    <p><?= $recipe->get_content() ?></p>
</div>

Answer:

Wasn’t able to test it but basically store results to $authors first, and in this way you can count it without recalling the method get_authors. While $cnt keeps track base 1 and can be compared directly on the length.

<?php

$authors = $recipe->get_authors();
$cnt = 0;
?>
<div class="four-sixths first">
    <a href="<?php echo 'URL' ?>"><img class="mb-20" src="<?= $recipe->get_thumbnail() ?>" alt=""/></a>
    <h2 class="mb-5"><?= $recipe->get_title() ?></h2>
    <span><?= $recipe->get_date() ?></span> -
        <?php foreach ($authors as $profile) { $cnt++; ?>
            <a href="<?= $profile->get_url() ?>"><?= $profile->get_name() ?></a><?php
                if ($cnt < count($authors)) echo ",";
            ?>
        <?php } ?>
    <p><?= $recipe->get_content() ?></p>
</div>