Log1x Log1x - 9 days ago 5
PHP Question

Loop through alphabetical array for an A-Z Index

This has been asked a couple times but none of the examples show it with proper HTML styling. I'm having some trouble getting the below code to wrap the items in

<ul></ul>
for each section. My current code does the
while
loop infinitely before switching letters and I'm not sure how to properly do it.

Here is my current code:

$range = range('A', 'Z');
if (!empty($terms)) {
foreach ($range as $letter) {
echo '<div class="column">';
echo '<h3>' . $letter . '</h3>';
echo '<ul>';
foreach ($terms as $term) {
while (strtoupper(substr($term->name, 0, 1)) == $letter) {
echo '<li><a href="' . home_url(get_term_link($term->term_id)) . '">' . $term->name . '</a></li>';
}
}
echo '</ul>';
echo '</div>';
}
}


Expected output:

<div class="column">
<h3>A</h3>
<ul>
<li><a href="#">Atom</a></li>
<li><a href="#">Awesome</a></li>
</ul>
</div>

<div class="column">
<h3>B</h3>
<ul>
<li><a href="#">Banana</a></li>
<li><a href="#">Bottle</a></li>
</ul>
</div>

<div class="column">
<h3>C</h3>
<p>No item found</p>
</div>

[...]

Answer

You're already looping within a loop, also the characters of strings in PHP can be accessed like an array.

if (!empty($terms)) {
  foreach (range('A', 'Z') as $letter) {
    echo '<div class="column">';
    echo '<h3>' . $letter . '</h3>';

    $matches = [];
    foreach ($terms as $term) {
      if(strtoupper($term->name[0]) == $letter){
        $matches[] = '<li><a href="' . home_url(get_term_link($term->term_id)) . '">' . $term->name  . '</a></li>';
      }
    }

    echo !empty($matches) ? '<ul>' . implode('', $matches) . '</ul>' : '<p>No item found</p>';
    echo '</div>';
  }
}
Comments