Search code examples
phpwordpresslaravel-5.3codeigniter-3

Loop through the Alphabet in PHP to group letters into ranges A-C, C-E etc


I want to create filters using the alphabet with 3-letter ranges like this: A-C,C-E,E-G etc

This is what I have so far:

function get_alphabet()
{
  $alphabet = '';
  for ($i=65; $i<=90; $i++) {  

    $letter = chr($i);
    $alphabet .= '<a title="filter results by letter '.$letter.'" 
href="/business/'.$letter.'"> ';
    $alphabet .= $letter;
    $alphabet .= '</a> | '; 
  }

  return $alphabet;
}
echo get_alphabet();

Solution

  • Try below code

    function get_alphabet()
    {
      $alphabet = '';
      for ($i=65; $i<=90; $i=$i+2) {  
    
        $letter = chr($i);
        $letter2 =($i+2>=90) ? chr(90) : chr($i+2);
    
        $links=$letter.'-'.$letter2;
        $alphabet .= '<a title="filter results by letter '.$links.'" 
    href="/business/'.$links.'"> ';
        $alphabet .= $links;
        $alphabet .= '</a> | '; 
    
      }
    
      return $alphabet;
    }
    echo get_alphabet();
    

    Output : A-C | C-E | E-G | G-I | I-K | K-M | M-O | O-Q | Q-S | S-U | U-W | W-Y | Y-Z |