Skip to content

Instantly share code, notes, and snippets.

@gpbeer
Last active July 25, 2021 19:16
Show Gist options
  • Save gpbeer/2c670f44888dac62cbe8c1b70dd85e22 to your computer and use it in GitHub Desktop.
Save gpbeer/2c670f44888dac62cbe8c1b70dd85e22 to your computer and use it in GitHub Desktop.
PHP Group array by first letter
<?php if (!empty($items)): ?>
<ul>
<?php $current_letter = ''; ?>
<?php foreach ($items as $item) : ?>
<?php $first_letter = mb_substr($item['post_title'], 0, 1, "UTF-8"); ?>
<?php if ($first_letter != $current_letter) : ?><li><?php endif; // group list ?>
<?php if ($first_letter != $current_letter) : ?>
<h2><?php echo $first_letter; ?></h2>
<?php $current_letter = $first_letter; ?>
<?php endif; ?>
<p class="mb5"><?php echo $item['post_title'];?></p>
<?php if ($first_letter != $current_letter) : ?></li><?php endif; // group list ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
@Qoraiche
Copy link

Many Thanks for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment