PHP Implode wrap in tags
Asked Answered
C

3

33

Been trying to google an answer but cant seem to find anything, I have the following...

<?php
    $values =   array_map('trim', get_post_custom_values($key));
    $value  =   implode($values,', ');
    echo "<div class='top-meta-vals'>".apply_filters(" $value\n", $value)."</div>";
?>

I want to wrap each and every $value in a span tag but im unsure how...

I tried,

<?php
$value = "<span>".implode($values,', ')."</span>";
?>

with no luck, can anybody give me an idea of where im going wrong?

Chittagong answered 26/3, 2012 at 13:5 Comment(2)
$value = '<span>'.implode('<span>, </span>', $values).'</span>';Alesandrini
Comment above is wrong. Should be '</span>, <span>' in implodeHormone
S
75

In this way you are wrapping the entire set in one span, you have to add the closing/opening tag to the implode:

$value = "<span>".implode('</span>,<span>', $values)."</span>";
Silicosis answered 26/3, 2012 at 13:7 Comment(4)
Just to mention : with empty $tags array it would become <span></span> string.Incubation
Flip the parameters to implode and then it's correct, should be: implode('</span>,<span>', $values)Lib
To resolve the empty $values issue resulting in $value as an empty span element you can echo trim( $value, '<span></span>');Rote
Got same problem today. Added additional empty() clause: empty($values) ? "" : "<span>".implode('</span>,<span>', $values)."</span>";Omni
I
21

You can use array_map function, smth like this:

$filter = function($tag){ return '<span>' . $tag . '</span>'; };
$spannedTags = array_map($filter, $tags);

End then just implode with ,.

Incubation answered 26/3, 2012 at 13:9 Comment(0)
A
8

Basically, this just implodes your values, using the 'glue' of span closed/open, and wraps it so the first and last items have their beginning/ending spans tags:

$value = "<span>" . implode("</span><span>", $values) . "</span>";
Alms answered 26/3, 2012 at 13:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.