I have an array like the following
1 => "Los Angeles"
2 => "California"
3 => "St. Louis"
4 => "Missouri"
5 => "Boston"
6 => "Massachusetts"
I want to change it to an associative array, so every odd entry index would be City and every even entry would be state. Let me know if this makes sense.
Based on the title you put, you want to have associative array but you want all index to be the same, that's not possible. Reading beyond the lines of your question and if I understand correctly, all odd items in your array are cities and the even items are state and you want to separate it? then try below:
<?php
$scrambled_city_state = array(
1 => "Los Angeles",
2 => "California",
3 => "St. Louis",
4 => "Missouri",
5 => "Boston",
6 => "Massachusetts"
);
$cities = array();
$states = array();
foreach ($scrambled_city_state as $key => $city_state) {
if ($key % 2 == 0) {
// state
$states[] = $city_state;
}
else {
// city
$cities[] = $city_state;
}
}
var_dump($cities, $states);
?>
output:
array(3) {
[0]=>
string(11) "Los Angeles"
[1]=>
string(9) "St. Louis"
[2]=>
string(6) "Boston"
}
array(3) {
[0]=>
string(10) "California"
[1]=>
string(8) "Missouri"
[2]=>
string(13) "Massachusetts"
}
Array keys can not have the same name. They would have to be 'city1', 'city2' etc
This solution will work for you
<?php
$myarray = array("1" => "Los Angeles" ,
"2" => "California" ,
"3" => "St. Louis" ,
"4" => "Missouri" ,
"5" => "Boston" ,
"6" => "Massachusetts");
var_dump($myarray);
?>
RESULT-array(6) { [1]=> string(11) "Los Angeles" [2]=> string(10) "California" [3]=> string(9) "St. Louis" [4]=> string(8) "Missouri" [5]=> string(6) "Boston" [6]=> string(13) "Massachusetts" }