3v4l.org

run code in 300+ PHP versions simultaneously
<?php $text = "Why end might ask civil again spoil. She dinner she our horses depend. Remember at children by reserved to vicinity. In affronting unreserved delightful simplicity ye. Law own advantage furniture continual sweetness bed agreeable perpetual. Oh song well four only head busy it. Afford son she had lively living. Tastes lovers myself too formal season our valley boy. Lived it their their walls might to by young."; // build $result = []; foreach( preg_split('![^a-zA-Z]+!', $text, -1, PREG_SPLIT_NO_EMPTY) as $word ) { $word = strtolower($word); $char = $word[0]; // not storing as the element's value but the key // takes care of doublets $result[$char][$word] = true; } // get keys & sort $result = array_map( function($e) { // remember? The actual words have been stored as the keys $e = array_keys($e); usort($e, 'strcasecmp'); return $e; }, $result ); // print var_export($result);
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
array ( 'w' => array ( 0 => 'walls', 1 => 'well', 2 => 'why', ), 'e' => array ( 0 => 'end', ), 'm' => array ( 0 => 'might', 1 => 'myself', ), 'a' => array ( 0 => 'advantage', 1 => 'afford', 2 => 'affronting', 3 => 'again', 4 => 'agreeable', 5 => 'ask', 6 => 'at', ), 'c' => array ( 0 => 'children', 1 => 'civil', 2 => 'continual', ), 's' => array ( 0 => 'season', 1 => 'she', 2 => 'simplicity', 3 => 'son', 4 => 'song', 5 => 'spoil', 6 => 'sweetness', ), 'd' => array ( 0 => 'delightful', 1 => 'depend', 2 => 'dinner', ), 'o' => array ( 0 => 'oh', 1 => 'only', 2 => 'our', 3 => 'own', ), 'h' => array ( 0 => 'had', 1 => 'head', 2 => 'horses', ), 'r' => array ( 0 => 'remember', 1 => 'reserved', ), 'b' => array ( 0 => 'bed', 1 => 'boy', 2 => 'busy', 3 => 'by', ), 't' => array ( 0 => 'tastes', 1 => 'their', 2 => 'to', 3 => 'too', ), 'v' => array ( 0 => 'valley', 1 => 'vicinity', ), 'i' => array ( 0 => 'in', 1 => 'it', ), 'u' => array ( 0 => 'unreserved', ), 'y' => array ( 0 => 'ye', 1 => 'young', ), 'l' => array ( 0 => 'law', 1 => 'lived', 2 => 'lively', 3 => 'living', 4 => 'lovers', ), 'f' => array ( 0 => 'formal', 1 => 'four', 2 => 'furniture', ), 'p' => array ( 0 => 'perpetual', ), )

preferences:
227.87 ms | 408 KiB | 327 Q