mysql - PHP - List pulled from one field exploding commas

433

The title may be a bit misleading, to be honest I don't know what this feature is called.

I have a field which will contain a list of a users skills in the database, the skills will be separated by commas.

When I then echo the field, I want each skill after the commas to be in a new list element.

So it'll echo like this in the HTML:

<ul>
<li>Cycling</li>
<li>Driving</li>
<li>Running</li>
</ul>

However in the field 'skills' it'll look like:

Cycling, Driving, Running

I read that you need to explode the comma however I have no idea how to accomplish it.

758

Answer

Solution:

Here's explode:

$activities = explode(',', $activities);  

Filter to trim the values of the array (so there's no whitespace on them) using array_map:

$activities = array_map('trim', $activities);

Then glue it back up with implode:

$activities = '<li>' . implode('</li><li>' . $activities) . '</li>';

Put it all together, with a bit of defensive programming:

$activities = explode(',', $activities);
if ( $activities ) {
    $activities = array_map('trim', $activities);
    $activities = '<li>' . implode('</li><li>' . $activities) . '</li>';
}
398

Answer

Solution:

This can be achieved withexplode (php documentation).

$activities = 'Cycling, Driving, Running';
$exploded = explode(', ', $activities);
foreach ($exploded as $activity) {
    echo '<li>' . $activity . '</li>';
}
770

Answer

Solution:

$list = "Cycling, Driving, Running";
$elements = explode(", ",$list);

echo "<ul>";
foreach($elements as $element){
    echo "<li>$element</li>";
}
echo "</ul>";
938

Answer

Solution:

I've got it working now! :)

Thanks to who contributed.

Code I used:

<ul >
  <?php
  $activities_q = "SELECT skills FROM users WHERE uid='".$row['uid']."'";
  $activities = $row['skills'];
  $exploded = explode(',', $activities);
  foreach ($exploded as $activity) {
    echo '<li >' . $activity . '</li>';
  }
?>
</ul>

People are also looking for solutions to the problem: php - Select all from MySql and join other

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.