3v4l.org

run code in 150+ php & hhvm versions
Bugs & Features
<?php $string = 'Spider-man|Spider-man 2|Spider-man 3|Apple|Google|Banana|Citrus'; $result = array(); foreach(explode('|', $string) as $item) { $firstLetter = $item[0]; if(!isset($result[$firstLetter])) { $result[$firstLetter] = array(); } $result[$firstLetter][] = $item; } ksort($result); var_dump($result);
Output for 4.3.0 - 7.1.0
array(5) { ["A"]=> array(1) { [0]=> string(5) "Apple" } ["B"]=> array(1) { [0]=> string(6) "Banana" } ["C"]=> array(1) { [0]=> string(6) "Citrus" } ["G"]=> array(1) { [0]=> string(6) "Google" } ["S"]=> array(3) { [0]=> string(10) "Spider-man" [1]=> string(12) "Spider-man 2" [2]=> string(12) "Spider-man 3" } }