Gautam Jha
Gautam Jha

Reputation: 1473

separating comma separated values in <a> by php

i have some values in comma separated like : $tag=jan,feb,mar,apr,may

Now i want to do this

<a href="xyz.php?tag=jan">jan</a> 
<a href="xyz.php?tag=feb">feb</a> 
<a href="xyz.php?tag=mar">mar</a> 
<a href="xyz.php?tag=apr">apr</a> 
<a href="xyz.php?tag=may">may</a> 

help me out of this. thank you in advance

Upvotes: 1

Views: 262

Answers (6)

Cristik
Cristik

Reputation: 32814

A "functional" approach, making use of explode(), array_map(), and implode():

$tags="jan,feb,mar,apr,may";
echo implode("\n",array_map(function($tag) {
    return "<a href=\"xyz.php?tag=$tag\">$tag</a>";
}, explode(',',$tags)))

Or, without an extra call to implode, with the help of array_reduce():

$tags="jan,feb,mar,apr,may";
echo array_reduce(explode(',',$tags), function($acc, $tag) {
    return $acc."<a href=\"xyz.php?tag=$tag\">$tag</a>\n";
}, '')

Ofcourse, if you already have the tags in the array format, then you can skip the explode.

Upvotes: 0

Albzi
Albzi

Reputation: 15609

You can use explode to put them in an array.

$tag = "jan,feb,mar,apr,may,jun,jul"; //etc

$months = explode(",", $tag);

The explode function will then set $months to look like this:

$months = [
    'jan',
    'feb',
    'mar',
    'apr',
    'may',
    'jun',
    'jul'
];

Then you can use foreach to loop through this new array you've created.

foreach($months as $month) {
    echo "<a href='xyz.php?tag=$month'>$month</a><br>";
}

Upvotes: 0

online Thomas
online Thomas

Reputation: 9381

foreach (explode(",", $tag) as $month) { //split by comma
echo '<a href="xyz.php?tag=' . $month . "</a>\n"; //just echo it
}

Upvotes: 0

Pupil
Pupil

Reputation: 23958

You can simply split the string by comma to get array of months.

Now, loop over the array and print the links with months.

<?php
$tag="jan,feb,mar,apr,may";
$tags = explode(',', $tag);
if (! empty($tags)) {
  foreach ($tags as $tag) {
  ?>
  <a href="xyz.php?tag=<?php echo $tag;?>"><?php echo $tag;?></a>   
  <?php
  }
}
?>

Upvotes: 0

Matt
Matt

Reputation: 2869

<?php
$tag="jan,feb,mar,apr,may";
$tags = explode(',', $tag); //Explode tags into an array
foreach($tags as $vals)//Loop through tags
{
    ?>
    <a href="xyz.php?tag=<?php echo $vals; ?>"><?php echo $vals; ?></a>
    <?php //Echo onto page
}
?>

Upvotes: 3

Amit Rajput
Amit Rajput

Reputation: 2059

Just do like this:

<?php
$tag='jan,feb,mar,apr,may';
foreach(explode(',', $tag) as $val){
echo '<a href="xyz.php?tag='.$val.'">'.$val.'</a><br>'; 
}
?>

Upvotes: 0

Related Questions