Skip to content
Advertisement

Split a comma delimited string into an array and display on html page

basically I’m making a page where the information from mySQL database will be displayed. I have a column named topics in the database where the string (VARCHAR) goes like this:

Marketing, Business, Law, Medicine, …

I’m trying to break up this string after a comma and display them in a single line one by one like this:

<h6>Marketing</h6>
<h6>Business</h6>
<h6>Law</h6>
<h6>Medicine</h6>
<h6>...</h6>

I already have a loop for other rows and I’m not sure if it’s possible to make a loop in the loop, I’m not even sure if what i’m trying to achieve is possible but I belive it is. Here goes my full PHP code:

<?php
include_once '../handlers/db_conn.php';

$sql = $conn->prepare("SELECT * FROM esc WHERE hosting_country = ?");
$sql->bind_param("s", $hosting_country);

$hosting_country = 'Poland';
$sql->execute();

$result = $sql->get_result();
$resultCheck = mysqli_num_rows($result);

if ($resultCheck > 0) {

} else {
  echo '<p class="not_found">Nothing Found</p>';
}

while($escrow = $result->fetch_assoc()) {

?>

<div class="col-lg-6 col-md-12 col-sm-12 col-12">
  <div class="sec1_col1">
    <h2><?php echo $escrow['project_name'] ?></h2>
    <i class="fi fi-br-world"></i>
    <h3><?php echo $escrow['hosting_country'] ?></h3>
    <i class="fi fi-sr-calendar-lines"></i>
    <h3><?php echo $escrow['start_date'] ?> - <?php echo $escrow['end_date'] ?></h3>
    <h4 class="objectives"><?php echo $escrow['objectives'] ?></h4>
    <h5>Topics</h5>
    <h6><?php echo $escrow['topics'] ?></h6>
    <hr>
    <a href="#">Read more</a>
  </div>
</div>

<?php
}
?>

I’m wondering if it’s possible to create another loop in this loop for element, separate this string after a comma and display one by one in tag? Any help would be greatly appreciated. Thanks.

EDIT

This is what I’m trying to achieve:

This is how I want it to look

Advertisement

Answer

Quite simple (and yes, you may have as many nested loops inside your code as you want):

Use explode to split your string, then loop over it.

<!-- inside your loop... -->
<h5>Topics</h5>
<?php foreach(explode(", ", $escrow["topics"]) as $topic) { ?>
<h6><?= $topic ?></h6>
<?php } ?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement