What are best practices for implementing a "group break" feature in PHP when displaying sorted data with different groups based on the first letter of a field?
When displaying sorted data with different groups based on the first letter of a field, a common practice is to implement a "group break" feature to visually separate the groups. This can be achieved by checking the first letter of each field value and displaying a group break header when the letter changes.
// Sample array of data sorted by a field
$data = [
['name' => 'Alice', 'age' => 25],
['name' => 'Bob', 'age' => 30],
['name' => 'Charlie', 'age' => 28],
['name' => 'David', 'age' => 22],
['name' => 'Eve', 'age' => 27],
['name' => 'Frank', 'age' => 31],
];
$prevLetter = '';
foreach ($data as $item) {
$firstLetter = strtoupper(substr($item['name'], 0, 1));
if ($firstLetter != $prevLetter) {
echo "<h2>Group $firstLetter</h2>";
$prevLetter = $firstLetter;
}
echo $item['name'] . ' - ' . $item['age'] . '<br>';
}
Keywords
Related Questions
- What are some best practices for creating SEO-friendly URLs in PHP without using Apache mod_rewrite?
- What are the best practices for error handling and user input validation in PHP when dealing with sensitive data like search queries?
- What best practices should be followed when writing PHP MySQL queries to avoid syntax errors?