There is a small dilemma on how to create a neat listing such as this: a, b, c, d
Sometimes you need it for programming reasons, SQL is often pretty unhelpful if you got an extra comma there. Sometimes you just want it that way because it looks nice. Usually you have values in an array to begin with.
$array = ('a', 'b', 'c', 'd');
Now you need to do soemthing with each entry, well, that screams foreach.
$array = ('a', 'b', 'c', 'd');
$out = '';
foreach ($array as $value)
{
$out .= $value . ', ';
}
But that gives you the dangling comma and a space at the end. So you could now trim that off the end (substr) or already do it the right way in the foreach. That could look something like this.
$array = ('a', 'b', 'c', 'd');
$out = '';
$first = true;
foreach ($array as $value)
{
if (true == $first)
{
$first = false;
}
else
{
$out .= ', ';
}
$out .= $value;
}
Now we also need to add a link around it.
$array = ('a', 'b', 'c', 'd');
$out = '';
$first = true;
foreach ($array as $value)
{
if (true == $first)
{
$first = false;
}
else
{
$out .= ', ';
}
$out .= '<a href="/' . $value . '/">' . $value . '</a>';
}
A lot of code and a lot of extra checks for not much gain really. Isn’t there a better way? After all there is only a need for this addition in between the parts of the array. If only there was a function that puts something between the pieces of an array. Ah but yes there is, and it’s called implode. If we had the first simple array and list this could be over rather quick like this.
$array = ('a', 'b', 'c', 'd');
$out = implode(', ', $array);
But we have this extra data we need around the array, so what do we do? Well first generate a new array, then implode of course, like this.
$array = ('a', 'b', 'c', 'd');
$temp = array();
foreach ($array as $value)
{
$temp[] = '<a href="/' . $value . '/">' . $value . '</a>';
}
$out = implode(', ', $temp);
unset($temp);
Much more comfortable and also much more readable now. First one round preparing, then gluing the pieces into the string. And of course, if you don’t need it anymore, unset the array or you will carry that data around the application for no reason.
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
You must be logged in to post a comment.