0

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.

1
  • Please, provide example of result array. Commented Dec 22, 2015 at 2:41

3 Answers 3

1

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is exactly what I needed!
1

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" }

Comments

0

Array keys can not have the same name. They would have to be 'city1', 'city2' etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.