Search code examples
phparrayssortingalphabeticalletter

PHP - splice array alphabetically after some letter


I´m looking for a solution to get all words (or numbers) from a sorted array AFTER some letter or number. I.e. all countries after letter K.

$countries = array(
'Luxembourg', 
'Germany', 
'France', 
'Spain', 
'Malta',
'Portugal', 
'Italy', 
'Switzerland', 
'Netherlands',  
'Belgium', 
'Norway', 
'Sweden', 
'Finland', 
'Poland',
'Lithuania', 
'United Kingdom', 
'Ireland', 
'Iceland',
'Hungary', 
'Greece', 
'Georgia'
);

sort($countries);

That will return Belgium, Finland, France, Georgia, Germany, Greece, Hungary, Iceland, Ireland, Italy, Lithuania, Luxembourg, Malta, Netherlands, Norway, ...

But I want only countries AFTER letter K: Lithuania, Luxembourg, Malta, Netherlands, Norway, ...

Any ideas?


Solution

  • Use the array_filter function to filter out the stuff you don't want.

    $result = array_filter( $countries, function( $country ) {
      return strtoupper($country{0}) > "K";
    });