I have an array of strings
$cities = ['New York', 'Boston', 'Los Angeles', 'Cincinnati', 'Chicago', 'Houston', 'Philadelphia', 'Dallas', 'Seattle'];
I want to retrieve all the strings that starts with letter A, then B, then C, and so on for each alphabet letters.
What is the best way to do it avoidng useless code repetitions?
You can create a temporary multidimensional array with first letter as index. Try -
$cities = ['New York', 'Boston', 'Los Angeles', 'Cincinnati', 'Chicago', 'Houston', 'Philadelphia', 'Dallas', 'Seattle'];
foreach($cities as $city) {
$first = substr($city, 0, 1);
$temp_cities[$first][] = $city;
}
var_dump($temp_cities);
Output
array(8) {
["N"]=>
array(1) {
[0]=>
string(8) "New York"
}
["B"]=>
array(1) {
[0]=>
string(6) "Boston"
}
["L"]=>
array(1) {
[0]=>
string(11) "Los Angeles"
}
["C"]=>
array(2) {
[0]=>
string(10) "Cincinnati"
[1]=>
string(7) "Chicago"
}
["H"]=>
array(1) {
[0]=>
string(7) "Houston"
}
["P"]=>
array(1) {
[0]=>
string(12) "Philadelphia"
}
["D"]=>
array(1) {
[0]=>
string(6) "Dallas"
}
["S"]=>
array(1) {
[0]=>
string(7) "Seattle"
}
}
To find cities start with 'C' do - var_dump($temp_cities['C'])