What are the potential pitfalls of using if-else statements for filtering data based on initial letters in PHP?

Using if-else statements for filtering data based on initial letters in PHP can become cumbersome and repetitive, especially if there are many conditions to check. An alternative approach is to use an associative array where the keys are the initial letters and the values are arrays of items that start with that letter. This allows for more efficient and cleaner code.

$data = ["apple", "banana", "carrot", "grape", "orange"];

$filteredData = [];

foreach ($data as $item) {
    $initialLetter = strtolower(substr($item, 0, 1));
    
    if (!isset($filteredData[$initialLetter])) {
        $filteredData[$initialLetter] = [];
    }
    
    $filteredData[$initialLetter][] = $item;
}

print_r($filteredData);