John Davidson

Separating php from html in foreach snippet

0 comments
Message:


Edit: solution was to add the missing equal signs to echo out variable (i.e., <?=). See comments below.


Following this format :


<ul>
<?php foreach($foo as $bar): ?>
<li> hi i'm <?=$bar;?> </li>
<? endforeach; ?>
</ul>

I want to convert the following into a similar, more MVC format of separating html and php to avoid echoing html, but unable to figure out how.


Original working code:


<? $i = 1; $tabsuffix = strtolower($content['tabs'][0]['label']);
foreach($content['tabs'] as $key => $tab){$tabid=$tab['label'] . "-" . $tabsuffix;
echo '<li class="nav-item" role="presentation">
<button class="nav-link ' . ($i == 1 ? "active" : "") . ' blob" id="pills-' . $tabid .
'-tab" data-bs-toggle="pill" data-bs-target="#pills-' . $tabid . '" type="button"
role="tab" aria-controls="pills-' . $tabid . '" aria-selected="true">
<h2 class="h4">' . $tab["label"]. '</h2>
</button></li>';
$i++;} ?>

Unsuccessful reformated version:


<?$i = 1; $tabsuffix = strtolower($content['tabs'][0]['label']);
foreach($content['tabs'] as $key => $tab):
$tabid=$tab['label'] . "-" . $tabsuffix; ?>
<li class="nav-item" role="presentation">
<button class="nav-link <?= ($i == 1 ? "active" : "")?> blob" id="pills-<?$tabid?>-tab"
data-bs-toggle="pill" data-bs-target="#pills-<?$tabid?>" type="button" role="tab"
aria-controls="pills-<?$tabid?>" aria-selected="true">
<h2 class="h4"><?$tab["label"]?></h2>
</button>
</li>
<?$i++; endforeach; ?>

Any suggestions would be appreciative.



My Answer:
$colors = array("red", "green", "blue");

foreach($colors as $color) {
?>


Rate this post

4 of 5 based on 8678 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us